@pagamio/frontend-commons-lib 0.8.217 → 0.8.218

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (108) hide show
  1. package/lib/api/index.d.ts +0 -2
  2. package/lib/api/index.js +0 -2
  3. package/lib/components/layout/Sidebar.js +24 -47
  4. package/lib/components/ui/Sheet.d.ts +1 -1
  5. package/lib/context/SidebarContext.d.ts +0 -10
  6. package/lib/dashboard-visuals/index.js +3 -10
  7. package/lib/dashboard-visuals/utils/chartOptions.js +1 -0
  8. package/lib/dashboard-visuals/visuals/Tile.js +2 -3
  9. package/lib/index.d.ts +0 -4
  10. package/lib/index.js +0 -23
  11. package/lib/styles.css +0 -212
  12. package/package.json +1 -7
  13. package/lib/api/TanstackQueryProvider.d.ts +0 -146
  14. package/lib/api/TanstackQueryProvider.js +0 -140
  15. package/lib/api/tanstackQuery.d.ts +0 -249
  16. package/lib/api/tanstackQuery.js +0 -299
  17. package/lib/dashboard-visuals-v2/DashboardWrapperV2.d.ts +0 -81
  18. package/lib/dashboard-visuals-v2/DashboardWrapperV2.js +0 -223
  19. package/lib/dashboard-visuals-v2/cards/CardGrid.d.ts +0 -22
  20. package/lib/dashboard-visuals-v2/cards/CardGrid.js +0 -27
  21. package/lib/dashboard-visuals-v2/cards/InfoCard.d.ts +0 -7
  22. package/lib/dashboard-visuals-v2/cards/InfoCard.js +0 -26
  23. package/lib/dashboard-visuals-v2/cards/MetricCard.d.ts +0 -7
  24. package/lib/dashboard-visuals-v2/cards/MetricCard.js +0 -37
  25. package/lib/dashboard-visuals-v2/cards/StatCard.d.ts +0 -7
  26. package/lib/dashboard-visuals-v2/cards/StatCard.js +0 -92
  27. package/lib/dashboard-visuals-v2/cards/TopItemsCard.d.ts +0 -7
  28. package/lib/dashboard-visuals-v2/cards/TopItemsCard.js +0 -34
  29. package/lib/dashboard-visuals-v2/cards/TransactionListCard.d.ts +0 -7
  30. package/lib/dashboard-visuals-v2/cards/TransactionListCard.js +0 -24
  31. package/lib/dashboard-visuals-v2/cards/index.d.ts +0 -9
  32. package/lib/dashboard-visuals-v2/cards/index.js +0 -9
  33. package/lib/dashboard-visuals-v2/charts/AreaChart.d.ts +0 -7
  34. package/lib/dashboard-visuals-v2/charts/AreaChart.js +0 -124
  35. package/lib/dashboard-visuals-v2/charts/BarChart.d.ts +0 -7
  36. package/lib/dashboard-visuals-v2/charts/BarChart.js +0 -106
  37. package/lib/dashboard-visuals-v2/charts/BaseChart.d.ts +0 -61
  38. package/lib/dashboard-visuals-v2/charts/BaseChart.js +0 -173
  39. package/lib/dashboard-visuals-v2/charts/DonutChart.d.ts +0 -7
  40. package/lib/dashboard-visuals-v2/charts/DonutChart.js +0 -108
  41. package/lib/dashboard-visuals-v2/charts/HeatmapChart.d.ts +0 -7
  42. package/lib/dashboard-visuals-v2/charts/HeatmapChart.js +0 -101
  43. package/lib/dashboard-visuals-v2/charts/LineChart.d.ts +0 -7
  44. package/lib/dashboard-visuals-v2/charts/LineChart.js +0 -109
  45. package/lib/dashboard-visuals-v2/charts/MixedChart.d.ts +0 -7
  46. package/lib/dashboard-visuals-v2/charts/MixedChart.js +0 -106
  47. package/lib/dashboard-visuals-v2/charts/PieChart.d.ts +0 -7
  48. package/lib/dashboard-visuals-v2/charts/PieChart.js +0 -10
  49. package/lib/dashboard-visuals-v2/charts/RadialChart.d.ts +0 -7
  50. package/lib/dashboard-visuals-v2/charts/RadialChart.js +0 -72
  51. package/lib/dashboard-visuals-v2/charts/index.d.ts +0 -12
  52. package/lib/dashboard-visuals-v2/charts/index.js +0 -12
  53. package/lib/dashboard-visuals-v2/components/DataFetchingVisual.d.ts +0 -0
  54. package/lib/dashboard-visuals-v2/components/DataFetchingVisual.js +0 -1
  55. package/lib/dashboard-visuals-v2/components/index.d.ts +0 -0
  56. package/lib/dashboard-visuals-v2/components/index.js +0 -1
  57. package/lib/dashboard-visuals-v2/hooks/index.d.ts +0 -4
  58. package/lib/dashboard-visuals-v2/hooks/index.js +0 -4
  59. package/lib/dashboard-visuals-v2/hooks/useChartData.d.ts +0 -72
  60. package/lib/dashboard-visuals-v2/hooks/useChartData.js +0 -122
  61. package/lib/dashboard-visuals-v2/index.d.ts +0 -10
  62. package/lib/dashboard-visuals-v2/index.js +0 -16
  63. package/lib/dashboard-visuals-v2/types/card.types.d.ts +0 -237
  64. package/lib/dashboard-visuals-v2/types/card.types.js +0 -30
  65. package/lib/dashboard-visuals-v2/types/chart.types.d.ts +0 -308
  66. package/lib/dashboard-visuals-v2/types/chart.types.js +0 -25
  67. package/lib/dashboard-visuals-v2/types/index.d.ts +0 -6
  68. package/lib/dashboard-visuals-v2/types/index.js +0 -6
  69. package/lib/dashboard-visuals-v2/utils/index.d.ts +0 -0
  70. package/lib/dashboard-visuals-v2/utils/index.js +0 -1
  71. package/lib/dashboard-visuals-v2/utils/propsTransformer.d.ts +0 -0
  72. package/lib/dashboard-visuals-v2/utils/propsTransformer.js +0 -1
  73. package/lib/dashboard-visuals-v2/visualRegistry.d.ts +0 -59
  74. package/lib/dashboard-visuals-v2/visualRegistry.js +0 -110
  75. package/lib/data-table-v2/DataTable.d.ts +0 -7
  76. package/lib/data-table-v2/DataTable.js +0 -206
  77. package/lib/data-table-v2/components/DataTableBody.d.ts +0 -19
  78. package/lib/data-table-v2/components/DataTableBody.js +0 -20
  79. package/lib/data-table-v2/components/DataTableEmpty.d.ts +0 -17
  80. package/lib/data-table-v2/components/DataTableEmpty.js +0 -13
  81. package/lib/data-table-v2/components/DataTableError.d.ts +0 -16
  82. package/lib/data-table-v2/components/DataTableError.js +0 -14
  83. package/lib/data-table-v2/components/DataTableHeader.d.ts +0 -15
  84. package/lib/data-table-v2/components/DataTableHeader.js +0 -31
  85. package/lib/data-table-v2/components/DataTableLoading.d.ts +0 -14
  86. package/lib/data-table-v2/components/DataTableLoading.js +0 -19
  87. package/lib/data-table-v2/components/DataTablePagination.d.ts +0 -36
  88. package/lib/data-table-v2/components/DataTablePagination.js +0 -20
  89. package/lib/data-table-v2/components/DataTableRowActions.d.ts +0 -13
  90. package/lib/data-table-v2/components/DataTableRowActions.js +0 -57
  91. package/lib/data-table-v2/components/DataTableSearch.d.ts +0 -19
  92. package/lib/data-table-v2/components/DataTableSearch.js +0 -33
  93. package/lib/data-table-v2/components/DataTableToolbar.d.ts +0 -54
  94. package/lib/data-table-v2/components/DataTableToolbar.js +0 -28
  95. package/lib/data-table-v2/components/index.d.ts +0 -12
  96. package/lib/data-table-v2/components/index.js +0 -12
  97. package/lib/data-table-v2/hooks/index.d.ts +0 -4
  98. package/lib/data-table-v2/hooks/index.js +0 -4
  99. package/lib/data-table-v2/hooks/useTableData.d.ts +0 -118
  100. package/lib/data-table-v2/hooks/useTableData.js +0 -210
  101. package/lib/data-table-v2/index.d.ts +0 -9
  102. package/lib/data-table-v2/index.js +0 -12
  103. package/lib/data-table-v2/types/index.d.ts +0 -296
  104. package/lib/data-table-v2/types/index.js +0 -1
  105. package/lib/data-table-v2/utils/export.d.ts +0 -26
  106. package/lib/data-table-v2/utils/export.js +0 -92
  107. package/lib/data-table-v2/utils/index.d.ts +0 -4
  108. package/lib/data-table-v2/utils/index.js +0 -4
@@ -1,140 +0,0 @@
1
- import { jsx as _jsx, jsxs as _jsxs } from "react/jsx-runtime";
2
- /**
3
- * @fileoverview TanStack Query Provider for the API client
4
- * Provides a configured QueryClient with sensible defaults
5
- */
6
- import { QueryClient, QueryClientProvider } from '@tanstack/react-query';
7
- import { ReactQueryDevtools } from '@tanstack/react-query-devtools';
8
- import { useMemo } from 'react';
9
- /**
10
- * Default configuration for the QueryClient
11
- * Matches the conservative caching strategy used in the SWR integration
12
- */
13
- export const DEFAULT_QUERY_CLIENT_OPTIONS = {
14
- queries: {
15
- /** Data is considered fresh for 5 minutes */
16
- staleTime: 5 * 60 * 1000,
17
- /** Garbage collection time - 10 minutes */
18
- gcTime: 10 * 60 * 1000,
19
- /** Don't refetch on window focus (matches SWR config) */
20
- refetchOnWindowFocus: false,
21
- /** Don't refetch on reconnect (matches SWR config) */
22
- refetchOnReconnect: false,
23
- /** Retry failed requests once */
24
- retry: 1,
25
- /** Retry delay */
26
- retryDelay: (attemptIndex) => Math.min(1000 * 2 ** attemptIndex, 30000),
27
- /** Don't refetch on mount if data exists */
28
- refetchOnMount: false,
29
- },
30
- mutations: {
31
- /** Retry failed mutations once */
32
- retry: 1,
33
- },
34
- };
35
- /**
36
- * Creates a configured QueryClient instance
37
- *
38
- * @example
39
- * ```tsx
40
- * // Create a custom query client
41
- * const queryClient = createQueryClient({
42
- * queries: {
43
- * staleTime: 10 * 60 * 1000, // 10 minutes
44
- * },
45
- * });
46
- * ```
47
- */
48
- export function createQueryClient(options) {
49
- return new QueryClient({
50
- defaultOptions: {
51
- queries: {
52
- ...DEFAULT_QUERY_CLIENT_OPTIONS.queries,
53
- ...options?.queries,
54
- },
55
- mutations: {
56
- ...DEFAULT_QUERY_CLIENT_OPTIONS.mutations,
57
- ...options?.mutations,
58
- },
59
- },
60
- });
61
- }
62
- /**
63
- * Provider component for TanStack Query
64
- * Wraps your application with a configured QueryClient
65
- *
66
- * @example
67
- * ```tsx
68
- * // Basic usage
69
- * function App() {
70
- * return (
71
- * <ApiQueryProvider>
72
- * <ApiProvider apiClient={apiClient}>
73
- * <YourApp />
74
- * </ApiProvider>
75
- * </ApiQueryProvider>
76
- * );
77
- * }
78
- *
79
- * // With custom configuration
80
- * function App() {
81
- * return (
82
- * <ApiQueryProvider
83
- * queryClientOptions={{
84
- * queries: {
85
- * staleTime: 10 * 60 * 1000, // 10 minutes
86
- * refetchOnWindowFocus: true,
87
- * },
88
- * }}
89
- * showDevtools={process.env.NODE_ENV === 'development'}
90
- * devtoolsPosition="bottom-right"
91
- * >
92
- * <ApiProvider apiClient={apiClient}>
93
- * <YourApp />
94
- * </ApiProvider>
95
- * </ApiQueryProvider>
96
- * );
97
- * }
98
- *
99
- * // With existing QueryClient
100
- * const queryClient = createQueryClient();
101
- *
102
- * function App() {
103
- * return (
104
- * <ApiQueryProvider queryClient={queryClient}>
105
- * <ApiProvider apiClient={apiClient}>
106
- * <YourApp />
107
- * </ApiProvider>
108
- * </ApiQueryProvider>
109
- * );
110
- * }
111
- * ```
112
- */
113
- export function ApiQueryProvider({ children, queryClient: existingQueryClient, queryClientOptions, showDevtools = process.env.NODE_ENV === 'development', devtoolsPosition = 'bottom', devtoolsInitialIsOpen = false, }) {
114
- // Create or use existing query client
115
- const queryClient = useMemo(() => existingQueryClient ?? createQueryClient(queryClientOptions), [existingQueryClient, queryClientOptions]);
116
- return (_jsxs(QueryClientProvider, { client: queryClient, children: [children, showDevtools && _jsx(ReactQueryDevtools, { initialIsOpen: devtoolsInitialIsOpen, position: devtoolsPosition })] }));
117
- }
118
- /**
119
- * Combined provider that includes both ApiQueryProvider and can be used
120
- * as a drop-in replacement when you want TanStack Query with your API client
121
- *
122
- * @example
123
- * ```tsx
124
- * import { CombinedApiQueryProvider, createApiClient } from '@pagamio/frontend-commons-lib';
125
- *
126
- * const apiClient = createApiClient({ ... });
127
- *
128
- * function App() {
129
- * return (
130
- * <CombinedApiQueryProvider
131
- * apiClient={apiClient}
132
- * showDevtools={true}
133
- * >
134
- * <YourApp />
135
- * </CombinedApiQueryProvider>
136
- * );
137
- * }
138
- * ```
139
- */
140
- export { ApiQueryProvider as TanStackQueryProvider };
@@ -1,249 +0,0 @@
1
- /**
2
- * @fileoverview TanStack Query integration for the API client
3
- * Provides hooks for data fetching, mutations, and cache management
4
- */
5
- import { type InfiniteData, type QueryKey, type UseInfiniteQueryOptions, type UseInfiniteQueryResult, type UseMutationOptions, type UseMutationResult, type UseQueryOptions, type UseQueryResult } from '@tanstack/react-query';
6
- import type { ApiErrorResponse, RequestConfig, SpringBootResponse } from './types';
7
- /**
8
- * Extended request config for TanStack Query hooks
9
- */
10
- export interface TanStackRequestConfig extends RequestConfig {
11
- /** HTTP method for the request */
12
- method?: 'GET' | 'POST' | 'PUT' | 'PATCH' | 'DELETE';
13
- }
14
- /**
15
- * Main TanStack Query hook that automatically inherits auth config
16
- * @template TData - Type of the expected response data
17
- * @template TError - Type of the error response (defaults to ApiErrorResponse)
18
- *
19
- * @example
20
- * ```tsx
21
- * function UsersList() {
22
- * const { data, isLoading, error } = useApiQuery<User[]>({
23
- * queryKey: ['users'],
24
- * endpoint: '/users',
25
- * });
26
- *
27
- * if (isLoading) return <div>Loading...</div>;
28
- * if (error) return <div>Error: {error.message}</div>;
29
- *
30
- * return (
31
- * <ul>
32
- * {data?.map(user => <li key={user.id}>{user.name}</li>)}
33
- * </ul>
34
- * );
35
- * }
36
- * ```
37
- */
38
- export declare function useApiQuery<TData = unknown, TError = ApiErrorResponse>(options: {
39
- /** Unique query key for caching */
40
- queryKey: QueryKey;
41
- /** API endpoint to fetch */
42
- endpoint: string;
43
- /** Request configuration */
44
- requestConfig?: TanStackRequestConfig;
45
- } & Omit<UseQueryOptions<TData, TError, TData, QueryKey>, 'queryKey' | 'queryFn'>): UseQueryResult<TData, TError>;
46
- /**
47
- * Paginated TanStack Query hook for Spring Boot style responses
48
- * @template TItem - Type of items in the paginated response
49
- * @template TError - Type of the error response
50
- *
51
- * @example
52
- * ```tsx
53
- * function PaginatedUsers() {
54
- * const { data, isLoading } = usePaginatedApiQuery<User>({
55
- * queryKey: ['users', { page: 0, size: 10 }],
56
- * endpoint: '/users?page=0&size=10',
57
- * });
58
- *
59
- * return (
60
- * <div>
61
- * {data?.content.map(user => <div key={user.id}>{user.name}</div>)}
62
- * <p>Total: {data?.totalElements}</p>
63
- * </div>
64
- * );
65
- * }
66
- * ```
67
- */
68
- export declare function usePaginatedApiQuery<TItem, TError = ApiErrorResponse>(options: {
69
- queryKey: QueryKey;
70
- endpoint: string;
71
- requestConfig?: TanStackRequestConfig;
72
- } & Omit<UseQueryOptions<SpringBootResponse<TItem>, TError, SpringBootResponse<TItem>, QueryKey>, 'queryKey' | 'queryFn'>): UseQueryResult<SpringBootResponse<TItem>, TError>;
73
- /**
74
- * Infinite query hook for infinite scrolling with Spring Boot pagination
75
- * @template TItem - Type of items in the paginated response
76
- * @template TError - Type of the error response
77
- *
78
- * @example
79
- * ```tsx
80
- * function InfiniteUsersList() {
81
- * const {
82
- * data,
83
- * fetchNextPage,
84
- * hasNextPage,
85
- * isFetchingNextPage,
86
- * } = useInfiniteApiQuery<User>({
87
- * queryKey: ['users', 'infinite'],
88
- * endpoint: '/users',
89
- * pageSize: 20,
90
- * });
91
- *
92
- * return (
93
- * <div>
94
- * {data?.pages.flatMap(page => page.content).map(user => (
95
- * <div key={user.id}>{user.name}</div>
96
- * ))}
97
- * {hasNextPage && (
98
- * <button onClick={() => fetchNextPage()} disabled={isFetchingNextPage}>
99
- * {isFetchingNextPage ? 'Loading...' : 'Load More'}
100
- * </button>
101
- * )}
102
- * </div>
103
- * );
104
- * }
105
- * ```
106
- */
107
- export declare function useInfiniteApiQuery<TItem, TError = ApiErrorResponse>(options: {
108
- queryKey: QueryKey;
109
- /** Base endpoint (page params will be appended) */
110
- endpoint: string;
111
- /** Number of items per page */
112
- pageSize?: number;
113
- /** Parameter name for page number (default: 'page') */
114
- pageParam?: string;
115
- /** Parameter name for page size (default: 'size') */
116
- sizeParam?: string;
117
- requestConfig?: TanStackRequestConfig;
118
- } & Omit<UseInfiniteQueryOptions<SpringBootResponse<TItem>, TError, InfiniteData<SpringBootResponse<TItem>>, QueryKey>, 'queryKey' | 'queryFn' | 'getNextPageParam' | 'getPreviousPageParam' | 'initialPageParam'>): UseInfiniteQueryResult<InfiniteData<SpringBootResponse<TItem>>, TError>;
119
- /**
120
- * Mutation types for the useApiQueryMutation hook
121
- */
122
- export type MutationType = 'POST' | 'PUT' | 'PATCH' | 'DELETE';
123
- /**
124
- * Variables passed to mutation function
125
- */
126
- export interface MutationVariables<TData = unknown> {
127
- /** API endpoint */
128
- endpoint: string;
129
- /** Request body data (not needed for DELETE) */
130
- data?: TData;
131
- /** Additional request config */
132
- config?: TanStackRequestConfig;
133
- }
134
- /**
135
- * Mutation hook for POST, PUT, PATCH, DELETE operations
136
- * @template TData - Type of the response data
137
- * @template TVariables - Type of the mutation variables
138
- * @template TError - Type of the error response
139
- *
140
- * @example
141
- * ```tsx
142
- * function CreateUserForm() {
143
- * const queryClient = useQueryClient();
144
- * const { mutate, isPending } = useApiQueryMutation<User, CreateUserDto>({
145
- * method: 'POST',
146
- * onSuccess: () => {
147
- * queryClient.invalidateQueries({ queryKey: ['users'] });
148
- * },
149
- * });
150
- *
151
- * const handleSubmit = (data: CreateUserDto) => {
152
- * mutate({ endpoint: '/users', data });
153
- * };
154
- *
155
- * return (
156
- * <form onSubmit={handleSubmit}>
157
- * // ...form fields
158
- * <button type="submit" disabled={isPending}>
159
- * {isPending ? 'Creating...' : 'Create User'}
160
- * </button>
161
- * </form>
162
- * );
163
- * }
164
- * ```
165
- */
166
- export declare function useApiQueryMutation<TData = unknown, TVariables = unknown, TError = ApiErrorResponse>(options: {
167
- /** HTTP method for the mutation */
168
- method: MutationType;
169
- /** Query keys to invalidate on success */
170
- invalidateKeys?: QueryKey[];
171
- } & Omit<UseMutationOptions<TData, TError, MutationVariables<TVariables>>, 'mutationFn'>): UseMutationResult<TData, TError, MutationVariables<TVariables>>;
172
- /**
173
- * Convenience hook for POST mutations
174
- */
175
- export declare function useApiPostMutation<TData = unknown, TVariables = unknown, TError = ApiErrorResponse>(options?: Omit<Parameters<typeof useApiQueryMutation<TData, TVariables, TError>>[0], 'method'>): UseMutationResult<TData, TError, MutationVariables<TVariables>>;
176
- /**
177
- * Convenience hook for PUT mutations
178
- */
179
- export declare function useApiPutMutation<TData = unknown, TVariables = unknown, TError = ApiErrorResponse>(options?: Omit<Parameters<typeof useApiQueryMutation<TData, TVariables, TError>>[0], 'method'>): UseMutationResult<TData, TError, MutationVariables<TVariables>>;
180
- /**
181
- * Convenience hook for PATCH mutations
182
- */
183
- export declare function useApiPatchMutation<TData = unknown, TVariables = unknown, TError = ApiErrorResponse>(options?: Omit<Parameters<typeof useApiQueryMutation<TData, TVariables, TError>>[0], 'method'>): UseMutationResult<TData, TError, MutationVariables<TVariables>>;
184
- /**
185
- * Convenience hook for DELETE mutations
186
- */
187
- export declare function useApiDeleteMutation<TData = unknown, TError = ApiErrorResponse>(options?: Omit<Parameters<typeof useApiQueryMutation<TData, never, TError>>[0], 'method'>): UseMutationResult<TData, TError, MutationVariables<never>>;
188
- /**
189
- * Hook for prefetching data
190
- *
191
- * @example
192
- * ```tsx
193
- * function UserLink({ userId }: { userId: string }) {
194
- * const prefetch = useApiPrefetch();
195
- *
196
- * return (
197
- * <Link
198
- * to={`/users/${userId}`}
199
- * onMouseEnter={() => prefetch({
200
- * queryKey: ['user', userId],
201
- * endpoint: `/users/${userId}`,
202
- * })}
203
- * >
204
- * View User
205
- * </Link>
206
- * );
207
- * }
208
- * ```
209
- */
210
- export declare function useApiPrefetch(): <TData = unknown>(options: {
211
- queryKey: QueryKey;
212
- endpoint: string;
213
- requestConfig?: TanStackRequestConfig;
214
- staleTime?: number;
215
- }) => Promise<void>;
216
- /**
217
- * Hook for accessing the query client with typed helpers
218
- *
219
- * @example
220
- * ```tsx
221
- * function RefreshButton() {
222
- * const { invalidate, setData, removeQueries } = useApiQueryClient();
223
- *
224
- * return (
225
- * <button onClick={() => invalidate(['users'])}>
226
- * Refresh Users
227
- * </button>
228
- * );
229
- * }
230
- * ```
231
- */
232
- export declare function useApiQueryClient(): {
233
- /** The underlying query client */
234
- queryClient: import("@tanstack/react-query").QueryClient;
235
- /** Invalidate queries by key */
236
- invalidate: (queryKey: QueryKey) => Promise<void>;
237
- /** Set query data directly */
238
- setData: <TData>(queryKey: QueryKey, data: TData) => unknown;
239
- /** Get cached query data */
240
- getData: <TData>(queryKey: QueryKey) => TData | undefined;
241
- /** Remove queries from cache */
242
- removeQueries: (queryKey: QueryKey) => void;
243
- /** Cancel ongoing queries */
244
- cancelQueries: (queryKey: QueryKey) => Promise<void>;
245
- /** Refetch queries */
246
- refetch: (queryKey: QueryKey) => Promise<void>;
247
- /** Reset queries to initial state */
248
- resetQueries: (queryKey: QueryKey) => Promise<void>;
249
- };
@@ -1,299 +0,0 @@
1
- /**
2
- * @fileoverview TanStack Query integration for the API client
3
- * Provides hooks for data fetching, mutations, and cache management
4
- */
5
- import { useInfiniteQuery, useMutation, useQuery, useQueryClient, } from '@tanstack/react-query';
6
- import { useApi } from './context';
7
- /**
8
- * Creates a fetcher function using the existing ApiClient
9
- * @template ResponseData - Expected response type
10
- */
11
- function useApiFetcher() {
12
- const api = useApi();
13
- return async (endpoint, config) => {
14
- switch (config?.method) {
15
- case 'POST':
16
- return api.post(endpoint, config.body ? JSON.parse(config.body.toString()) : undefined, config);
17
- case 'PUT':
18
- return api.put(endpoint, config.body ? JSON.parse(config.body.toString()) : undefined, config);
19
- case 'PATCH':
20
- return api.patch(endpoint, config.body ? JSON.parse(config.body.toString()) : undefined, config);
21
- case 'DELETE':
22
- return api.delete(endpoint, config);
23
- default:
24
- return api.get(endpoint, config);
25
- }
26
- };
27
- }
28
- /**
29
- * Main TanStack Query hook that automatically inherits auth config
30
- * @template TData - Type of the expected response data
31
- * @template TError - Type of the error response (defaults to ApiErrorResponse)
32
- *
33
- * @example
34
- * ```tsx
35
- * function UsersList() {
36
- * const { data, isLoading, error } = useApiQuery<User[]>({
37
- * queryKey: ['users'],
38
- * endpoint: '/users',
39
- * });
40
- *
41
- * if (isLoading) return <div>Loading...</div>;
42
- * if (error) return <div>Error: {error.message}</div>;
43
- *
44
- * return (
45
- * <ul>
46
- * {data?.map(user => <li key={user.id}>{user.name}</li>)}
47
- * </ul>
48
- * );
49
- * }
50
- * ```
51
- */
52
- export function useApiQuery(options) {
53
- const fetcher = useApiFetcher();
54
- const { queryKey, endpoint, requestConfig, ...queryOptions } = options;
55
- return useQuery({
56
- queryKey,
57
- queryFn: () => fetcher(endpoint, requestConfig),
58
- ...queryOptions,
59
- });
60
- }
61
- /**
62
- * Paginated TanStack Query hook for Spring Boot style responses
63
- * @template TItem - Type of items in the paginated response
64
- * @template TError - Type of the error response
65
- *
66
- * @example
67
- * ```tsx
68
- * function PaginatedUsers() {
69
- * const { data, isLoading } = usePaginatedApiQuery<User>({
70
- * queryKey: ['users', { page: 0, size: 10 }],
71
- * endpoint: '/users?page=0&size=10',
72
- * });
73
- *
74
- * return (
75
- * <div>
76
- * {data?.content.map(user => <div key={user.id}>{user.name}</div>)}
77
- * <p>Total: {data?.totalElements}</p>
78
- * </div>
79
- * );
80
- * }
81
- * ```
82
- */
83
- export function usePaginatedApiQuery(options) {
84
- return useApiQuery(options);
85
- }
86
- /**
87
- * Infinite query hook for infinite scrolling with Spring Boot pagination
88
- * @template TItem - Type of items in the paginated response
89
- * @template TError - Type of the error response
90
- *
91
- * @example
92
- * ```tsx
93
- * function InfiniteUsersList() {
94
- * const {
95
- * data,
96
- * fetchNextPage,
97
- * hasNextPage,
98
- * isFetchingNextPage,
99
- * } = useInfiniteApiQuery<User>({
100
- * queryKey: ['users', 'infinite'],
101
- * endpoint: '/users',
102
- * pageSize: 20,
103
- * });
104
- *
105
- * return (
106
- * <div>
107
- * {data?.pages.flatMap(page => page.content).map(user => (
108
- * <div key={user.id}>{user.name}</div>
109
- * ))}
110
- * {hasNextPage && (
111
- * <button onClick={() => fetchNextPage()} disabled={isFetchingNextPage}>
112
- * {isFetchingNextPage ? 'Loading...' : 'Load More'}
113
- * </button>
114
- * )}
115
- * </div>
116
- * );
117
- * }
118
- * ```
119
- */
120
- export function useInfiniteApiQuery(options) {
121
- const fetcher = useApiFetcher();
122
- const { queryKey, endpoint, pageSize = 20, pageParam = 'page', sizeParam = 'size', requestConfig, ...queryOptions } = options;
123
- // Build endpoint with pagination params
124
- const buildEndpoint = (page) => {
125
- const separator = endpoint.includes('?') ? '&' : '?';
126
- return `${endpoint}${separator}${pageParam}=${page}&${sizeParam}=${pageSize}`;
127
- };
128
- return useInfiniteQuery({
129
- queryKey,
130
- queryFn: ({ pageParam: page }) => fetcher(buildEndpoint(page), requestConfig),
131
- initialPageParam: 0,
132
- getNextPageParam: (lastPage) => {
133
- if (lastPage.last)
134
- return undefined;
135
- return lastPage.number + 1;
136
- },
137
- getPreviousPageParam: (firstPage) => {
138
- if (firstPage.first)
139
- return undefined;
140
- return firstPage.number - 1;
141
- },
142
- ...queryOptions,
143
- });
144
- }
145
- /**
146
- * Mutation hook for POST, PUT, PATCH, DELETE operations
147
- * @template TData - Type of the response data
148
- * @template TVariables - Type of the mutation variables
149
- * @template TError - Type of the error response
150
- *
151
- * @example
152
- * ```tsx
153
- * function CreateUserForm() {
154
- * const queryClient = useQueryClient();
155
- * const { mutate, isPending } = useApiQueryMutation<User, CreateUserDto>({
156
- * method: 'POST',
157
- * onSuccess: () => {
158
- * queryClient.invalidateQueries({ queryKey: ['users'] });
159
- * },
160
- * });
161
- *
162
- * const handleSubmit = (data: CreateUserDto) => {
163
- * mutate({ endpoint: '/users', data });
164
- * };
165
- *
166
- * return (
167
- * <form onSubmit={handleSubmit}>
168
- * // ...form fields
169
- * <button type="submit" disabled={isPending}>
170
- * {isPending ? 'Creating...' : 'Create User'}
171
- * </button>
172
- * </form>
173
- * );
174
- * }
175
- * ```
176
- */
177
- export function useApiQueryMutation(options) {
178
- const api = useApi();
179
- const queryClient = useQueryClient();
180
- const { method, invalidateKeys, ...mutationOptions } = options;
181
- return useMutation({
182
- mutationFn: async ({ endpoint, data, config }) => {
183
- switch (method) {
184
- case 'POST':
185
- return api.post(endpoint, data, config);
186
- case 'PUT':
187
- return api.put(endpoint, data, config);
188
- case 'PATCH':
189
- return api.patch(endpoint, data, config);
190
- case 'DELETE':
191
- return api.delete(endpoint, config);
192
- default:
193
- throw new Error(`Unsupported mutation method: ${method}`);
194
- }
195
- },
196
- onSuccess: async () => {
197
- // Invalidate specified query keys
198
- if (invalidateKeys?.length) {
199
- await Promise.all(invalidateKeys.map((key) => queryClient.invalidateQueries({ queryKey: key })));
200
- }
201
- },
202
- ...mutationOptions,
203
- });
204
- }
205
- /**
206
- * Convenience hook for POST mutations
207
- */
208
- export function useApiPostMutation(options) {
209
- return useApiQueryMutation({ method: 'POST', ...options });
210
- }
211
- /**
212
- * Convenience hook for PUT mutations
213
- */
214
- export function useApiPutMutation(options) {
215
- return useApiQueryMutation({ method: 'PUT', ...options });
216
- }
217
- /**
218
- * Convenience hook for PATCH mutations
219
- */
220
- export function useApiPatchMutation(options) {
221
- return useApiQueryMutation({ method: 'PATCH', ...options });
222
- }
223
- /**
224
- * Convenience hook for DELETE mutations
225
- */
226
- export function useApiDeleteMutation(options) {
227
- return useApiQueryMutation({ method: 'DELETE', ...options });
228
- }
229
- /**
230
- * Hook for prefetching data
231
- *
232
- * @example
233
- * ```tsx
234
- * function UserLink({ userId }: { userId: string }) {
235
- * const prefetch = useApiPrefetch();
236
- *
237
- * return (
238
- * <Link
239
- * to={`/users/${userId}`}
240
- * onMouseEnter={() => prefetch({
241
- * queryKey: ['user', userId],
242
- * endpoint: `/users/${userId}`,
243
- * })}
244
- * >
245
- * View User
246
- * </Link>
247
- * );
248
- * }
249
- * ```
250
- */
251
- export function useApiPrefetch() {
252
- const queryClient = useQueryClient();
253
- const fetcher = useApiFetcher();
254
- return (options) => {
255
- const { queryKey, endpoint, requestConfig, staleTime } = options;
256
- return queryClient.prefetchQuery({
257
- queryKey,
258
- queryFn: () => fetcher(endpoint, requestConfig),
259
- staleTime,
260
- });
261
- };
262
- }
263
- /**
264
- * Hook for accessing the query client with typed helpers
265
- *
266
- * @example
267
- * ```tsx
268
- * function RefreshButton() {
269
- * const { invalidate, setData, removeQueries } = useApiQueryClient();
270
- *
271
- * return (
272
- * <button onClick={() => invalidate(['users'])}>
273
- * Refresh Users
274
- * </button>
275
- * );
276
- * }
277
- * ```
278
- */
279
- export function useApiQueryClient() {
280
- const queryClient = useQueryClient();
281
- return {
282
- /** The underlying query client */
283
- queryClient,
284
- /** Invalidate queries by key */
285
- invalidate: (queryKey) => queryClient.invalidateQueries({ queryKey }),
286
- /** Set query data directly */
287
- setData: (queryKey, data) => queryClient.setQueryData(queryKey, data),
288
- /** Get cached query data */
289
- getData: (queryKey) => queryClient.getQueryData(queryKey),
290
- /** Remove queries from cache */
291
- removeQueries: (queryKey) => queryClient.removeQueries({ queryKey }),
292
- /** Cancel ongoing queries */
293
- cancelQueries: (queryKey) => queryClient.cancelQueries({ queryKey }),
294
- /** Refetch queries */
295
- refetch: (queryKey) => queryClient.refetchQueries({ queryKey }),
296
- /** Reset queries to initial state */
297
- resetQueries: (queryKey) => queryClient.resetQueries({ queryKey }),
298
- };
299
- }