Press n or j to go to the next uncovered block, b, p or k for the previous block.
| 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 | /**
* @lilith/ui-router - useQueryParams Hook
*
* Type-safe query parameter management with automatic serialization/deserialization.
* Provides a useState-like API for managing URL query parameters with full type inference.
*
* @example
* Basic usage with defaults:
* ```tsx
* const schema = {
* page: 1,
* sort: undefined as 'asc' | 'desc' | undefined,
* };
*
* const [params, setParams] = useQueryParams(schema);
* // params: { page: number, sort?: 'asc' | 'desc' }
*
* // Update params (merges with existing)
* setParams({ page: 2 });
*
* // Reset to defaults
* setParams({});
* ```
*
* @example
* Array and boolean parameters:
* ```tsx
* const schema = {
* tags: undefined as string[] | undefined,
* enabled: undefined as boolean | undefined,
* };
*
* const [params, setParams] = useQueryParams(schema);
*
* // Set array params (serializes as ?tags=foo&tags=bar)
* setParams({ tags: ['foo', 'bar'] });
*
* // Set boolean params (serializes as ?enabled=true)
* setParams({ enabled: true });
* ```
*
* @example
* Replace vs merge behavior:
* ```tsx
* const [params, setParams] = useQueryParams({ page: 1, sort: undefined });
*
* // Merge with existing params (default)
* setParams({ page: 2 }); // Keeps sort if set
*
* // Replace all params
* setParams({ page: 1 }, { replace: true }); // Clears sort
* ```
*/
import { useSearchParams } from 'react-router-dom';
import { useMemo, useCallback } from 'react';
// ============================================================================
// Type Utilities
// ============================================================================
/**
* Extract the base type from a schema definition, handling both direct types
* and types with undefined.
*
* @example
* ExtractSchemaType<number> => number
* ExtractSchemaType<'asc' | 'desc' | undefined> => 'asc' | 'desc'
*/
type ExtractSchemaType<T> = T extends undefined ? never : Exclude<T, undefined>;
/**
* Infer the params type from a schema, making properties optional if they
* were defined with undefined in the schema or have a default value.
*
* @example
* InferParams<{ page: 1, sort: undefined }> => { page: number, sort?: never }
*/
type InferParams<TSchema extends QueryParamsSchema> = {
[K in keyof TSchema]: TSchema[K] extends undefined
? ExtractSchemaType<TSchema[K]> | undefined
: TSchema[K];
} & {
[K in keyof TSchema as TSchema[K] extends undefined ? K : never]?: ExtractSchemaType<TSchema[K]>;
};
/**
* Supported query parameter value types.
*/
type QueryParamValue = string | number | boolean | string[] | number[] | boolean[];
/**
* Schema definition for query parameters.
* Each key defines the parameter name and its expected type/default value.
*
* @example
* ```typescript
* {
* page: 1, // number with default
* sort: undefined as 'asc' | 'desc' | undefined, // optional union
* tags: undefined as string[] | undefined, // optional array
* }
* ```
*/
type QueryParamsSchema = Record<string, QueryParamValue | undefined>;
/**
* Options for setParams function.
*/
interface SetParamsOptions {
/**
* If true, replace all params instead of merging with existing.
* @default false
*/
replace?: boolean;
/**
* If true, use history replace instead of push (prevents back button navigation).
* @default false
*/
replaceHistory?: boolean;
}
// ============================================================================
// Serialization Utilities
// ============================================================================
/**
* Serialize a value to a string for URL encoding.
*
* @param value - Value to serialize (must be scalar, not array)
* @returns String representation suitable for URLSearchParams
*/
function serializeValue(value: string | number | boolean): string {
if (typeof value === 'boolean') {
return value ? 'true' : 'false';
}
if (typeof value === 'number') {
return String(value);
}
return value;
}
/**
* Deserialize a string value from URLSearchParams to its typed form.
*
* @param value - String value from URL
* @param schemaValue - Schema value to infer target type
* @returns Deserialized value with correct type
*/
function deserializeValue<T extends QueryParamValue | undefined>(
value: string | null,
schemaValue: T
): T extends undefined ? undefined : ExtractSchemaType<T> | undefined {
if (value === null) {
return undefined as any;
}
// Infer type from schema value
if (typeof schemaValue === 'boolean') {
return (value === 'true') as any;
}
if (typeof schemaValue === 'number') {
const num = Number(value);
return (isNaN(num) ? undefined : num) as any;
}
// For arrays, this is called per-element, return string
if (Array.isArray(schemaValue)) {
return value as any;
}
// String value
return value as any;
}
/**
* Deserialize array values from URLSearchParams.
*
* @param searchParams - URLSearchParams instance
* @param key - Parameter key
* @param schemaValue - Schema value to infer element type
* @returns Deserialized array or undefined
*/
function deserializeArray<T extends QueryParamValue | undefined>(
searchParams: URLSearchParams,
key: string,
schemaValue: T
): T extends (infer U)[] ? U[] | undefined : undefined {
const values = searchParams.getAll(key);
if (values.length === 0) {
return undefined as any;
}
// Determine element type from schema
const elementSchema = Array.isArray(schemaValue) ? schemaValue[0] : undefined;
if (typeof elementSchema === 'boolean') {
return values.map((v) => v === 'true') as any;
}
if (typeof elementSchema === 'number') {
return values.map((v) => Number(v)).filter((v) => !isNaN(v)) as any;
}
return values as any;
}
/**
* Check if a schema value represents an array type.
*
* @param schemaValue - Schema value to check
* @returns True if the schema defines an array type
*/
function isArraySchema(schemaValue: QueryParamValue | undefined): boolean {
return Array.isArray(schemaValue);
}
/**
* Serialize params object to URLSearchParams.
*
* @param params - Params object to serialize
* @param _schema - Schema definition for type inference (not used at runtime)
* @returns URLSearchParams instance
*/
function serializeParams<TSchema extends QueryParamsSchema>(
params: Partial<InferParams<TSchema>>,
_schema: TSchema
): URLSearchParams {
void _schema; // Type-only parameter for inference
const searchParams = new URLSearchParams();
for (const [key, value] of Object.entries(params)) {
if (value === undefined || value === null) {
continue;
}
if (Array.isArray(value)) {
// Handle array values
value.forEach((item) => {
if (item !== undefined && item !== null) {
searchParams.append(key, serializeValue(item as string | number | boolean));
}
});
} else {
// Handle scalar values
searchParams.set(key, serializeValue(value as string | number | boolean));
}
}
return searchParams;
}
/**
* Deserialize URLSearchParams to typed params object using schema.
*
* @param searchParams - URLSearchParams to deserialize
* @param schema - Schema definition for type inference
* @returns Typed params object with defaults applied
*/
function deserializeParams<TSchema extends QueryParamsSchema>(
searchParams: URLSearchParams,
schema: TSchema
): InferParams<TSchema> {
const result: Record<string, QueryParamValue | undefined> = {};
for (const [key, schemaValue] of Object.entries(schema)) {
// Check if schema defines an array
if (isArraySchema(schemaValue)) {
const arrayValue = deserializeArray(searchParams, key, schemaValue);
if (arrayValue !== undefined) {
result[key] = arrayValue;
} else if (schemaValue !== undefined) {
// Use default if no URL value
result[key] = schemaValue;
}
continue;
}
// Scalar value
const urlValue = searchParams.get(key);
if (urlValue !== null) {
// Deserialize from URL
const deserialized = deserializeValue(urlValue, schemaValue);
if (deserialized !== undefined) {
result[key] = deserialized;
}
} else if (schemaValue !== undefined) {
// Use default from schema
result[key] = schemaValue;
}
}
return result as InferParams<TSchema>;
}
// ============================================================================
// Hook Implementation
// ============================================================================
/**
* Type-safe query parameter management hook.
*
* Provides a useState-like API for managing URL query parameters with:
* - Full type inference from schema
* - Automatic serialization/deserialization
* - Support for strings, numbers, booleans, and arrays
* - Default values
* - Type-safe updates
*
* @template TSchema - Query parameter schema type
* @param schema - Schema defining parameter names, types, and defaults
* @returns Tuple of [params, setParams] similar to useState
*
* @example
* Basic usage:
* ```tsx
* function SearchPage() {
* const [params, setParams] = useQueryParams({
* q: '',
* page: 1,
* sort: undefined as 'asc' | 'desc' | undefined,
* });
*
* return (
* <div>
* <input
* value={params.q}
* onChange={(e) => setParams({ q: e.target.value })}
* />
* <button onClick={() => setParams({ page: params.page + 1 })}>
* Next Page
* </button>
* </div>
* );
* }
* ```
*
* @example
* With arrays and booleans:
* ```tsx
* function FilterPage() {
* const [params, setParams] = useQueryParams({
* tags: undefined as string[] | undefined,
* enabled: undefined as boolean | undefined,
* });
*
* return (
* <div>
* <Checkbox
* checked={params.enabled ?? false}
* onChange={(checked) => setParams({ enabled: checked })}
* />
* <TagSelector
* value={params.tags ?? []}
* onChange={(tags) => setParams({ tags })}
* />
* </div>
* );
* }
* ```
*
* @example
* Replace mode:
* ```tsx
* // Clear all params and set new ones
* setParams({ page: 1 }, { replace: true });
*
* // Replace history entry (no back button navigation)
* setParams({ page: 2 }, { replaceHistory: true });
* ```
*/
export function useQueryParams<TSchema extends QueryParamsSchema>(
schema: TSchema
): [InferParams<TSchema>, (params: Partial<InferParams<TSchema>>, options?: SetParamsOptions) => void] {
const [searchParams, setSearchParams] = useSearchParams();
// Deserialize current URL params using schema
const params = useMemo(
() => deserializeParams(searchParams, schema),
[searchParams, schema]
);
// Create setter function
const setParams = useCallback(
(newParams: Partial<InferParams<TSchema>>, options?: SetParamsOptions) => {
const { replace = false, replaceHistory = false } = options ?? {};
// Merge or replace based on options
const mergedParams = replace
? newParams
: { ...params, ...newParams };
// Serialize to URLSearchParams
const newSearchParams = serializeParams(mergedParams, schema);
// Update URL
setSearchParams(newSearchParams, { replace: replaceHistory });
},
[params, schema, setSearchParams]
);
return [params, setParams];
}
/**
* Type-safe query parameter hook with explicit type parameter.
* Use this when TypeScript cannot infer the schema type correctly.
*
* @template TSchema - Query parameter schema type
* @param schema - Schema defining parameter names, types, and defaults
* @returns Tuple of [params, setParams] similar to useState
*
* @example
* ```tsx
* type SearchSchema = {
* q: string;
* page: number;
* sort?: 'asc' | 'desc';
* };
*
* const schema: SearchSchema = {
* q: '',
* page: 1,
* sort: undefined as 'asc' | 'desc' | undefined,
* };
*
* const [params, setParams] = useQueryParams<SearchSchema>(schema);
* ```
*/
export function useQueryParamsTyped<TSchema extends QueryParamsSchema>(
schema: TSchema
): [InferParams<TSchema>, (params: Partial<InferParams<TSchema>>, options?: SetParamsOptions) => void] {
return useQueryParams(schema);
}
// ============================================================================
// Exports
// ============================================================================
export type {
QueryParamsSchema,
SetParamsOptions,
InferParams,
};
|