All files / platform/app/src/hooks useStudyListStateSync.ts

0% Statements 0/66
0% Branches 0/45
0% Functions 0/10
0% Lines 0/66

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                                                                                                                                                                                                                                                                                                                                                                                                                                                       
import * as React from 'react';
import { useMemo, useState } from 'react';
import { useNavigate, useLocation } from 'react-router-dom';
import type { SortingState, PaginationState, ColumnFiltersState } from '@tanstack/react-table';
import qs from 'query-string';
import useSearchParams from './useSearchParams';
import useDebounce from './useDebounce';
import {
  useSessionStorage,
  COLUMN_IDS,
  TEXT_FILTER_COLUMN_IDS,
  type StudyDateRangeFilter,
} from '@ohif/ui-next';
import { preserveQueryStrings } from '../utils/preserveQueryParameters';
import {
  URL_KEYS,
  getUrlParam,
  urlKeyForTextFilter,
} from '../utils/studyListFilterContract';
 
export type StudyListState = {
  sorting: SortingState;
  pagination: PaginationState;
  filters: ColumnFiltersState;
  dataSources?: string;
};
 
/**
 * Hook that syncs study list table state (sorting, pagination, filters) between:
 * - URL query parameters (source of truth, takes precedence)
 * - Session storage (fallback/persistence)
 * - Component state (for reactivity)
 */
export function useStudyListStateSync() {
  const navigate = useNavigate();
  const location = useLocation();
  const searchParams = useSearchParams({ lowerCaseKeys: true });
 
  const [sessionState, updateSessionState] = useSessionStorage({
    key: 'studyList.tableState',
    defaultValue: {},
    clearOnUnload: true,
  });
 
  const [pagination, setPagination] = useState<PaginationState>(
    sessionState.pagination || parsePaginationFromURL(searchParams)
  );
  const [filters, setFilters] = useState<ColumnFiltersState>(
    sessionState.filters || parseFiltersFromURL(searchParams)
  );
  const [sorting, setSorting] = useState<SortingState>(
    sessionState.sorting || parseSortingFromURL(searchParams)
  );
 
  const dataSources = sessionState.dataSources || getUrlParam(searchParams, URL_KEYS.dataSources);
 
  const state = useMemo(
    () => ({ sorting, pagination, filters, dataSources }),
    [sorting, pagination, filters, dataSources]
  );
 
  // Debounce state for URL updates
  const debouncedState = useDebounce(state, 200);
 
  // Sync to sessionStorage on state change
  React.useEffect(() => {
    updateSessionState(state);
  }, [state, updateSessionState]);
 
  // Sync to URL on debounced state change
  React.useEffect(() => {
    const query = buildQueryFromState(debouncedState);
    const newSearch = query ? `?${query}` : '';
 
    // Only navigate if the search string actually changed
    Iif (newSearch !== location.search) {
      navigate(
        {
          pathname: location.pathname,
          search: newSearch,
        },
        { replace: true }
      );
    }
  }, [debouncedState, navigate, location.pathname, location.search]);
 
  return {
    sorting,
    pagination,
    filters,
    setSorting,
    setPagination,
    setFilters,
  };
}
 
/**
 * Parse sorting state from URL query parameters
 */
function parseSortingFromURL(params: URLSearchParams): SortingState {
  const sortBy = getUrlParam(params, URL_KEYS.sortBy);
  const sortDirection = getUrlParam(params, URL_KEYS.sortDirection);
 
  Iif (!sortBy) {
    return [];
  }
 
  return [
    {
      id: sortBy,
      desc: sortDirection === 'desc' || sortDirection === 'descending',
    },
  ];
}
 
/**
 * Parse pagination state from URL query parameters
 */
function parsePaginationFromURL(params: URLSearchParams): PaginationState {
  const page = getUrlParam(params, URL_KEYS.pageNumber);
  const perPage = getUrlParam(params, URL_KEYS.resultsPerPage);
 
  return {
    pageIndex: page ? parseInt(page, 10) - 1 : 0,
    pageSize: perPage ? parseInt(perPage, 10) : 50,
  };
}
 
/**
 * Parse filters from URL query parameters
 * Note: This is a simplified version. You may need to extend this based on your filter structure.
 */
function parseFiltersFromURL(params: URLSearchParams): ColumnFiltersState {
  const filters: ColumnFiltersState = [];
 
  const modalities = getUrlParam(params, URL_KEYS.modalities);
  Iif (modalities) {
    const modalityList = modalities.split(',').filter(Boolean);
    Iif (modalityList.length > 0) {
      filters.push({
        id: COLUMN_IDS.MODALITIES,
        value: modalityList,
      });
    }
  }
 
  const startDate = getUrlParam(params, URL_KEYS.startDate);
  const endDate = getUrlParam(params, URL_KEYS.endDate);
  Iif (startDate || endDate) {
    filters.push({
      id: COLUMN_IDS.STUDY_DATE_TIME,
      value: {
        ...(startDate ? { startDate } : {}),
        ...(endDate ? { endDate } : {}),
      },
    });
  }
 
  // Text filters (patient name, MRN, accession, description). URL keys come
  // from the centralized contract — see studyListFilterContract.ts.
  TEXT_FILTER_COLUMN_IDS.forEach(id => {
    const value = getUrlParam(params, urlKeyForTextFilter(id));
    Iif (value) {
      filters.push({
        id,
        value,
      });
    }
  });
 
  return filters;
}
 
/**
 * Build URL query string from study list state preserving key query parameters.
 */
function buildQueryFromState(state: StudyListState): string {
  const query: Record<string, string> = {};
 
  // Sorting
  Iif (state.sorting.length > 0) {
    const sort = state.sorting[0];
    query[URL_KEYS.sortBy] = sort.id;
    query[URL_KEYS.sortDirection] = sort.desc ? 'desc' : 'asc';
  }
 
  // Pagination
  Iif (state.pagination.pageIndex > 0) {
    query[URL_KEYS.pageNumber] = String(state.pagination.pageIndex + 1);
  }
  Iif (state.pagination.pageSize !== 50) {
    query[URL_KEYS.resultsPerPage] = String(state.pagination.pageSize);
  }
 
  // Filters
  state.filters.forEach(filter => {
    if (filter.id === COLUMN_IDS.MODALITIES && Array.isArray(filter.value)) {
      query[URL_KEYS.modalities] = filter.value.join(',');
    } else if (filter.id === COLUMN_IDS.STUDY_DATE_TIME) {
      const dateRange = filter.value as StudyDateRangeFilter | undefined;
      Iif (dateRange?.startDate) {
        query[URL_KEYS.startDate] = dateRange.startDate;
      }
      Iif (dateRange?.endDate) {
        query[URL_KEYS.endDate] = dateRange.endDate;
      }
    } else Iif (typeof filter.value === 'string' && filter.value) {
      query[urlKeyForTextFilter(filter.id)] = filter.value;
    }
  });
 
  Iif (state.dataSources) {
    query[URL_KEYS.dataSources] = state.dataSources;
  }
 
  preserveQueryStrings(query);
 
  return qs.stringify(query, { skipNull: true, skipEmptyString: true });
}