All files / src/common/hooks useUrlParams.ts

83.79% Statements 181/216
76.59% Branches 36/47
41.66% Functions 5/12
83.79% Lines 181/216

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 3001x             1x 1x 1x                                       1x 90x 90x 90x 90x 90x     90x 90x     90x 90x   90x 596x     596x       596x 582x 596x           14x 1x 14x   13x 13x 596x   90x 90x     90x 90x 90x 90x     90x     90x 12x 12x   78x   78x 78x 4x     4x 13x 13x   13x 13x     13x 13x 13x 13x 11x 13x   2x   2x   2x 2x 2x     2x 13x   4x 4x 78x 78x 90x 90x 90x         90x 90x 1x 1x 1x 1x 1x 90x 90x     90x 85x 85x 85x 85x 85x 85x 85x 90x 90x     90x     90x 90x 1x 1x 90x 90x   90x     90x 2x 2x 10x 10x 2x 90x     90x 1x 90x     90x 90x 568x 568x 568x 90x 90x   90x 90x 90x 90x 90x 90x 90x 90x 90x 90x 90x     2x 2x       2x       2x 2x     13x 13x 1x 1x   13x 1x 1x   13x 4x 4x 4x   7x 7x     1x 75x 75x 75x 75x 75x 75x 75x 75x 75x 75x 75x 75x 75x 75x 75x 75x 75x 75x 75x 75x 75x 75x 75x 75x 75x 75x 75x 75x 75x 75x 75x 75x 75x 75x 75x 75x 75x 75x 75x 75x 75x     1x                                              
import {
  orderDirectionValidator,
  positiveIntegerValidator,
  sanitizeUrlParam,
  sortFieldValidator,
  type Validator
} from '@common/utils/urlParamValidation';
import { useCallback, useMemo, useRef } from 'react';
import { useSearchParams } from 'react-router-dom';
import { DependencyValidator, ValidationRules } from '../utils/dependencyValidation.ts';
 
export type ParamValue = string | number | boolean | string[] | null | undefined;
 
export interface ParamConfig<T extends Record<string, ParamValue>> {
  [key: string]: {
    defaultValue?: T[keyof T];
    serialize?: (value: T[keyof T]) => string | null;
    deserialize?: (value: string) => T[keyof T];
    omitIfDefault?: boolean;
    validator?: Validator<any>;
    sanitize?: boolean;
  };
}
 
export interface UseUrlParamsOptions {
  replace?: boolean; // Use replace instead of push for navigation
  debounceMs?: number; // Debounce URL updates
}
 
export function useUrlParams<T extends Record<string, ParamValue>>(
  config: ParamConfig<T>,
  options: UseUrlParamsOptions = {}
) {
  const [searchParams, setSearchParams] = useSearchParams();
  const { replace = true } = options;
 
  // Track last params to prevent unnecessary updates
  const lastParamsRef = useRef<string>('');
  const paramsRef = useRef<T>({} as T);
 
  // Parse current URL parameters based on config
  const params = useMemo(() => {
    const result = {} as T;
 
    for (const [key, paramConfig] of Object.entries(config)) {
      let urlValue = searchParams.get(key);
 
      // Sanitize the URL value if sanitization is enabled
      if (urlValue && paramConfig.sanitize) {
        urlValue = sanitizeUrlParam(urlValue);
      }
 
      if (urlValue === null) {
        result[key as keyof T] = paramConfig.defaultValue as T[keyof T];
      } else if (paramConfig.validator) {
        // Use custom validator if provided
        const validationResult = paramConfig.validator(urlValue, paramConfig.defaultValue);
        result[key as keyof T] = validationResult.isValid && validationResult.value !== undefined
          ? validationResult.value
          : paramConfig.defaultValue as T[keyof T];
      } else if (paramConfig.deserialize) {
        result[key as keyof T] = paramConfig.deserialize(urlValue);
      } else {
        // Default deserialization logic
        result[key as keyof T] = deserializeValue(urlValue, paramConfig.defaultValue) as T[keyof T];
      }
    }
 
    return result;
  }, [searchParams, config]);
 
  // Update URL parameters
  const updateParams = useCallback(
    (updates: Partial<T> | ((current: T) => Partial<T>)) => {
      const currentParams = paramsRef.current;
      const newParams = typeof updates === 'function' ? updates(currentParams) : updates;
 
      // Create string representation to compare with last params
      const newParamsString = JSON.stringify(newParams);
 
      // Prevent unnecessary updates if params haven't changed
      if (lastParamsRef.current === newParamsString) {
        return;
      }
 
      lastParamsRef.current = newParamsString;
 
      setSearchParams(
        (prevParams) => {
          const newSearchParams = new URLSearchParams(prevParams);
 
          // Update each parameter
          for (const [key, value] of Object.entries(newParams)) {
            const paramConfig = config[key];
            if (!paramConfig) continue;
 
            const defaultValue = paramConfig.defaultValue;
            const omitIfDefault = paramConfig.omitIfDefault ?? true;
 
            // Check if we should omit this parameter
            if (
              omitIfDefault &&
              (value === defaultValue || value === null || value === undefined)
            ) {
              newSearchParams.delete(key);
            } else {
              // Serialize the value
              const serializedValue = paramConfig.serialize
                ? paramConfig.serialize(value as T[keyof T])
                : serializeValue(value);
 
              if (serializedValue !== null) {
                newSearchParams.set(key, serializedValue);
              } else {
                newSearchParams.delete(key);
              }
            }
          }
 
          return newSearchParams;
        },
        { replace }
      );
    },
    [config, setSearchParams, replace]
  );
 
  // Update a single parameter
  // IMPORTANT: This useCallback MUST have empty dependencies [] to prevent infinite re-renders.
  // DO NOT add params or other dependencies to the dependencies array.
  const updateParam = useCallback(
    <K extends keyof T>(key: K, value: T[K] | ((current: T[K]) => T[K])) => {
      const currentValue = paramsRef.current[key];
      const newValue =
        typeof value === 'function' ? (value as (current: T[K]) => T[K])(currentValue) : value;
      updateParams({ [key]: newValue } as Partial<T>);
    },
    [updateParams, paramsRef]
  );
 
  // Create dependency validator for this hook
  const dependencyValidator = useMemo(() =>
    new DependencyValidator({
      errorPrefix: 'useUrlParams dependency validation failed',
      rules: [
        ValidationRules.noDependencies('getParam'),
        ValidationRules.specificDependencies('updateParam', [updateParams, paramsRef])
      ]
    }),
    [updateParams, paramsRef]
  );
 
  // Validate dependencies to prevent infinite loops
  dependencyValidator.validate('updateParam', [updateParams, paramsRef]);
 
  // Get a single parameter
  const getParam = useCallback(
    <K extends keyof T>(key: K): T[K] => {
      return paramsRef.current[key];
    },
    [paramsRef]
  );
  // Validate that getParam has empty dependencies to prevent infinite re-renders
  dependencyValidator.validate('getParam', []);
 
  // Reset all parameters to defaults
  const resetParams = useCallback(() => {
    const defaultParams = {} as Partial<T>;
    for (const [key, paramConfig] of Object.entries(config)) {
      defaultParams[key as keyof T] = paramConfig.defaultValue as T[keyof T];
    }
    updateParams(defaultParams);
  }, [config, updateParams]);
 
  // Clear all parameters
  const clearParams = useCallback(() => {
    setSearchParams(new URLSearchParams(), { replace });
  }, [setSearchParams, replace]);
 
  // Check if current params differ from defaults
  const hasNonDefaultParams = useMemo(() => {
    return Object.entries(config).some(([key, paramConfig]) => {
      const currentValue = params[key as keyof T];
      const defaultValue = paramConfig.defaultValue;
      return currentValue !== defaultValue;
    });
  }, [params, config]);
 
  return {
    params,
    updateParams,
    updateParam,
    getParam,
    resetParams,
    clearParams,
    hasNonDefaultParams,
    searchParams, // Raw search params for advanced use cases
  };
}
 
// Default serialization logic
function serializeValue(value: ParamValue): string | null {
  if (value === null || value === undefined) {
    return null;
  }
 
  if (Array.isArray(value)) {
    return value.length > 0 ? value.join(',') : null;
  }
 
  return String(value);
}
 
// Default deserialization logic
function deserializeValue(value: string, defaultValue: ParamValue): ParamValue {
  if (Array.isArray(defaultValue)) {
    return value ? value.split(',').filter(Boolean) : [];
  }
 
  if (typeof defaultValue === 'boolean') {
    return value === 'true';
  }
 
  if (typeof defaultValue === 'number') {
    const num = Number(value);
    return isNaN(num) ? defaultValue : num;
  }
 
  return value;
}
 
// Specialized hook for inbox filters
export function useInboxUrlParams() {
  return useUrlParams({
    filter: {
      defaultValue: 'all' as const,
      omitIfDefault: true,
    },
    source: {
      defaultValue: null as string | null,
      omitIfDefault: true,
      serialize: (value: string | null) => value || '',
      deserialize: (value: string) => value || null,
    },
    time: {
      defaultValue: 'all' as const,
      omitIfDefault: true,
    },
    tags: {
      defaultValue: [] as string[],
      omitIfDefault: true,
      serialize: (value: string[]) => value.join(','),
      deserialize: (value: string) => (value ? value.split(',').filter(Boolean) : []),
    },
    groups: {
      defaultValue: [] as string[],
      omitIfDefault: true,
      serialize: (value: string[]) => value.join(','),
      deserialize: (value: string) => (value ? value.split(',').filter(Boolean) : []),
    },
    sort: {
      defaultValue: 'received_at' as const,
      omitIfDefault: true,
      validator: sortFieldValidator,
      sanitize: true,
    },
    order: {
      defaultValue: 'desc' as const,
      omitIfDefault: true,
      validator: orderDirectionValidator,
      sanitize: true,
    },
  });
}
 
// Hook for reading queue URL params
export function useReadingQueueUrlParams() {
  return useUrlParams({
    page: {
      defaultValue: 1,
      omitIfDefault: true,
      validator: positiveIntegerValidator,
      sanitize: true,
      deserialize: (value: string) => Math.max(1, parseInt(value, 10) || 1),
    },
    sort: {
      defaultValue: 'created_at' as const,
      omitIfDefault: true,
      validator: sortFieldValidator,
      sanitize: true,
    },
    order: {
      defaultValue: 'desc' as const,
      omitIfDefault: true,
      validator: orderDirectionValidator,
      sanitize: true,
    },
  });
}