@checkstack/ui 0.1.0 → 0.2.1

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.
package/CHANGELOG.md CHANGED
@@ -1,5 +1,138 @@
1
1
  # @checkstack/ui
2
2
 
3
+ ## 0.2.1
4
+
5
+ ### Patch Changes
6
+
7
+ - 7a23261: ## TanStack Query Integration
8
+
9
+ Migrated all frontend components to use `usePluginClient` hook with TanStack Query integration, replacing the legacy `forPlugin()` pattern.
10
+
11
+ ### New Features
12
+
13
+ - **`usePluginClient` hook**: Provides type-safe access to plugin APIs with `.useQuery()` and `.useMutation()` methods
14
+ - **Automatic request deduplication**: Multiple components requesting the same data share a single network request
15
+ - **Built-in caching**: Configurable stale time and cache duration per query
16
+ - **Loading/error states**: TanStack Query provides `isLoading`, `error`, `isRefetching` states automatically
17
+ - **Background refetching**: Stale data is automatically refreshed when components mount
18
+
19
+ ### Contract Changes
20
+
21
+ All RPC contracts now require `operationType: "query"` or `operationType: "mutation"` metadata:
22
+
23
+ ```typescript
24
+ const getItems = proc()
25
+ .meta({ operationType: "query", access: [access.read] })
26
+ .output(z.array(itemSchema))
27
+ .query();
28
+
29
+ const createItem = proc()
30
+ .meta({ operationType: "mutation", access: [access.manage] })
31
+ .input(createItemSchema)
32
+ .output(itemSchema)
33
+ .mutation();
34
+ ```
35
+
36
+ ### Migration
37
+
38
+ ```typescript
39
+ // Before (forPlugin pattern)
40
+ const api = useApi(myPluginApiRef);
41
+ const [items, setItems] = useState<Item[]>([]);
42
+ useEffect(() => {
43
+ api.getItems().then(setItems);
44
+ }, [api]);
45
+
46
+ // After (usePluginClient pattern)
47
+ const client = usePluginClient(MyPluginApi);
48
+ const { data: items, isLoading } = client.getItems.useQuery({});
49
+ ```
50
+
51
+ ### Bug Fixes
52
+
53
+ - Fixed `rpc.test.ts` test setup for middleware type inference
54
+ - Fixed `SearchDialog` to use `setQuery` instead of deprecated `search` method
55
+ - Fixed null→undefined warnings in notification and queue frontends
56
+
57
+ - Updated dependencies [7a23261]
58
+ - @checkstack/frontend-api@0.2.0
59
+ - @checkstack/common@0.3.0
60
+
61
+ ## 0.2.0
62
+
63
+ ### Minor Changes
64
+
65
+ - 9faec1f: # Unified AccessRule Terminology Refactoring
66
+
67
+ This release completes a comprehensive terminology refactoring from "permission" to "accessRule" across the entire codebase, establishing a consistent and modern access control vocabulary.
68
+
69
+ ## Changes
70
+
71
+ ### Core Infrastructure (`@checkstack/common`)
72
+
73
+ - Introduced `AccessRule` interface as the primary access control type
74
+ - Added `accessPair()` helper for creating read/manage access rule pairs
75
+ - Added `access()` builder for individual access rules
76
+ - Replaced `Permission` type with `AccessRule` throughout
77
+
78
+ ### API Changes
79
+
80
+ - `env.registerPermissions()` → `env.registerAccessRules()`
81
+ - `meta.permissions` → `meta.access` in RPC contracts
82
+ - `usePermission()` → `useAccess()` in frontend hooks
83
+ - Route `permission:` field → `accessRule:` field
84
+
85
+ ### UI Changes
86
+
87
+ - "Roles & Permissions" tab → "Roles & Access Rules"
88
+ - "You don't have permission..." → "You don't have access..."
89
+ - All permission-related UI text updated
90
+
91
+ ### Documentation & Templates
92
+
93
+ - Updated 18 documentation files with AccessRule terminology
94
+ - Updated 7 scaffolding templates with `accessPair()` pattern
95
+ - All code examples use new AccessRule API
96
+
97
+ ## Migration Guide
98
+
99
+ ### Backend Plugins
100
+
101
+ ```diff
102
+ - import { permissionList } from "./permissions";
103
+ - env.registerPermissions(permissionList);
104
+ + import { accessRules } from "./access";
105
+ + env.registerAccessRules(accessRules);
106
+ ```
107
+
108
+ ### RPC Contracts
109
+
110
+ ```diff
111
+ - .meta({ userType: "user", permissions: [permissions.read.id] })
112
+ + .meta({ userType: "user", access: [access.read] })
113
+ ```
114
+
115
+ ### Frontend Hooks
116
+
117
+ ```diff
118
+ - const canRead = accessApi.usePermission(permissions.read.id);
119
+ + const canRead = accessApi.useAccess(access.read);
120
+ ```
121
+
122
+ ### Routes
123
+
124
+ ```diff
125
+ - permission: permissions.entityRead.id,
126
+ + accessRule: access.read,
127
+ ```
128
+
129
+ ### Patch Changes
130
+
131
+ - Updated dependencies [9faec1f]
132
+ - Updated dependencies [f533141]
133
+ - @checkstack/common@0.2.0
134
+ - @checkstack/frontend-api@0.1.0
135
+
3
136
  ## 0.1.0
4
137
 
5
138
  ### Minor Changes
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@checkstack/ui",
3
- "version": "0.1.0",
3
+ "version": "0.2.1",
4
4
  "type": "module",
5
5
  "main": "src/index.ts",
6
6
  "dependencies": {
@@ -3,13 +3,10 @@ import { ShieldAlert } from "lucide-react";
3
3
  import { Card, CardHeader, CardTitle, CardContent } from "./Card";
4
4
  import { cn } from "../utils";
5
5
 
6
- export const PermissionDenied: React.FC<{
6
+ export const AccessDenied: React.FC<{
7
7
  message?: string;
8
8
  className?: string;
9
- }> = ({
10
- message = "You do not have permission to view this page.",
11
- className,
12
- }) => {
9
+ }> = ({ message = "You do not have access to this page.", className }) => {
13
10
  return (
14
11
  <div
15
12
  className={cn(
@@ -0,0 +1,97 @@
1
+ import React from "react";
2
+ import { AccessDenied } from "./AccessDenied";
3
+ import { LoadingSpinner } from "./LoadingSpinner";
4
+
5
+ /**
6
+ * Props for the AccessGate component.
7
+ */
8
+ export interface AccessGateProps {
9
+ /**
10
+ * The access rule ID to check for access.
11
+ */
12
+ accessRuleId: string;
13
+ /**
14
+ * Content to render when access is granted.
15
+ */
16
+ children: React.ReactNode;
17
+ /**
18
+ * Custom fallback to render when access is denied.
19
+ * If not provided and showDenied is false, renders nothing.
20
+ */
21
+ fallback?: React.ReactNode;
22
+ /**
23
+ * If true, shows a AccessDenied component when access is denied.
24
+ * Useful for entire page sections. Overridden by fallback if provided.
25
+ */
26
+ showDenied?: boolean;
27
+ /**
28
+ * Custom message to show in the AccessDenied component.
29
+ */
30
+ deniedMessage?: string;
31
+ /**
32
+ * Hook to check access. Must be provided by the consumer.
33
+ * This allows the component to be used without depending on auth-frontend directly.
34
+ */
35
+ useAccess: (accessRuleId: string) => { loading: boolean; allowed: boolean };
36
+ }
37
+
38
+ /**
39
+ * Conditionally renders children based on whether the user has a required access rule.
40
+ *
41
+ * @example
42
+ * // Hide content if access denied
43
+ * <AccessGate accessRuleId="catalog.manage" useAccess={accessApi.useAccess}>
44
+ * <ManageButton />
45
+ * </AccessGate>
46
+ *
47
+ * @example
48
+ * // Show access denied message
49
+ * <AccessGate
50
+ * accessRuleId="catalog.read"
51
+ * useAccess={accessApi.useAccess}
52
+ * showDenied
53
+ * deniedMessage="You don't have access to view the catalog."
54
+ * >
55
+ * <CatalogList />
56
+ * </AccessGate>
57
+ *
58
+ * @example
59
+ * // Custom fallback
60
+ * <AccessGate
61
+ * accessRuleId="admin.manage"
62
+ * useAccess={accessApi.useAccess}
63
+ * fallback={<p>Admin access required</p>}
64
+ * >
65
+ * <AdminPanel />
66
+ * </AccessGate>
67
+ */
68
+ export const AccessGate: React.FC<AccessGateProps> = ({
69
+ accessRuleId,
70
+ children,
71
+ fallback,
72
+ showDenied = false,
73
+ deniedMessage,
74
+ useAccess,
75
+ }) => {
76
+ const { loading, allowed } = useAccess(accessRuleId);
77
+
78
+ if (loading) {
79
+ return <LoadingSpinner size="sm" />;
80
+ }
81
+
82
+ if (!allowed) {
83
+ if (fallback) {
84
+ return <>{fallback}</>;
85
+ }
86
+ if (showDenied) {
87
+ return (
88
+ <AccessDenied
89
+ message={deniedMessage ?? `You don't have access: ${accessRuleId}`}
90
+ />
91
+ );
92
+ }
93
+ return <></>;
94
+ }
95
+
96
+ return <>{children}</>;
97
+ };
@@ -2,13 +2,15 @@ import React, { useState, useRef, useEffect } from "react";
2
2
  import { NavLink } from "react-router-dom";
3
3
  import { ChevronDown } from "lucide-react";
4
4
  import { cn } from "../utils";
5
- import { useApi, permissionApiRef } from "@checkstack/frontend-api";
5
+ import { useApi, accessApiRef } from "@checkstack/frontend-api";
6
+ import type { AccessRule } from "@checkstack/common";
6
7
 
7
8
  export interface NavItemProps {
8
9
  to?: string;
9
10
  label: string;
10
11
  icon?: React.ReactNode;
11
- permission?: string;
12
+ /** Access rule to check - if not provided, always shows */
13
+ accessRule?: AccessRule;
12
14
  children?: React.ReactNode;
13
15
  className?: string;
14
16
  }
@@ -17,7 +19,7 @@ export const NavItem: React.FC<NavItemProps> = ({
17
19
  to,
18
20
  label,
19
21
  icon,
20
- permission,
22
+ accessRule,
21
23
  children,
22
24
  className,
23
25
  }) => {
@@ -25,11 +27,17 @@ export const NavItem: React.FC<NavItemProps> = ({
25
27
  const containerRef = useRef<HTMLDivElement>(null);
26
28
 
27
29
  // Always call hooks at top level
28
- // We assume permissionApi is available if we use it. Safe fallback?
29
- // ApiProvider guarantees it if registered. App.tsx registers a default.
30
- const permissionApi = useApi(permissionApiRef);
31
- const { allowed, loading } = permissionApi.usePermission(permission || "");
32
- const hasAccess = permission ? allowed : true;
30
+ const accessApi = useApi(accessApiRef);
31
+
32
+ // Create a dummy access rule for when accessRule is undefined
33
+ const dummyRule: AccessRule = {
34
+ id: "",
35
+ resource: "",
36
+ level: "read",
37
+ description: "",
38
+ };
39
+ const { allowed, loading } = accessApi.useAccess(accessRule ?? dummyRule);
40
+ const hasAccess = accessRule ? allowed : true;
33
41
 
34
42
  // Handle click outside for dropdown
35
43
  useEffect(() => {
@@ -4,7 +4,7 @@ import {
4
4
  PageHeader,
5
5
  PageContent,
6
6
  LoadingSpinner,
7
- PermissionDenied,
7
+ AccessDenied,
8
8
  } from "..";
9
9
 
10
10
  interface PageLayoutProps {
@@ -39,7 +39,7 @@ export const PageLayout: React.FC<PageLayoutProps> = ({
39
39
  }) => {
40
40
  // If loading is explicitly true, show loading state
41
41
  // If loading is undefined and allowed is false, also show loading state
42
- // (this prevents "Access Denied" flash when permissions are still being fetched)
42
+ // (this prevents "Access Denied" flash when access rules are still being fetched)
43
43
  const isLoading =
44
44
  loading === true || (loading === undefined && allowed === false);
45
45
 
@@ -56,13 +56,13 @@ export const PageLayout: React.FC<PageLayoutProps> = ({
56
56
  );
57
57
  }
58
58
 
59
- // Only show permission denied when loading is explicitly false and allowed is false
59
+ // Only show access denied when loading is explicitly false and allowed is false
60
60
  if (allowed === false) {
61
61
  return (
62
62
  <Page>
63
63
  <PageHeader title={title} subtitle={subtitle} actions={actions} />
64
64
  <PageContent>
65
- <PermissionDenied />
65
+ <AccessDenied />
66
66
  </PageContent>
67
67
  </Page>
68
68
  );
@@ -1,14 +1,24 @@
1
1
  import * as React from "react";
2
- import {
3
- usePagination,
4
- type UsePaginationOptions,
5
- type PaginationState,
6
- } from "../hooks/usePagination";
2
+ import { type PaginationState } from "../hooks/usePagination";
7
3
  import { Pagination } from "./Pagination";
8
4
  import { cn } from "../utils";
9
5
 
10
- export interface PaginatedListProps<TResponse, TItem, TExtraParams = object>
11
- extends UsePaginationOptions<TResponse, TItem, TExtraParams> {
6
+ export interface PaginatedListProps<TItem> {
7
+ /**
8
+ * Items to display
9
+ */
10
+ items: TItem[];
11
+
12
+ /**
13
+ * Loading state
14
+ */
15
+ loading: boolean;
16
+
17
+ /**
18
+ * Pagination state from usePagination hook
19
+ */
20
+ pagination: PaginationState;
21
+
12
22
  /**
13
23
  * Render function for the items
14
24
  */
@@ -64,23 +74,31 @@ export interface PaginatedListProps<TResponse, TItem, TExtraParams = object>
64
74
  }
65
75
 
66
76
  /**
67
- * All-in-one paginated list component with automatic data fetching.
77
+ * Paginated list component for rendering paginated data.
78
+ * Use with usePagination() hook and TanStack Query.
68
79
  *
69
80
  * @example
70
81
  * ```tsx
82
+ * const pagination = usePagination({ defaultLimit: 20 });
83
+ * const { data, isLoading } = notificationClient.getNotifications.useQuery({
84
+ * limit: pagination.limit,
85
+ * offset: pagination.offset,
86
+ * });
87
+ * usePaginationSync(pagination, data?.total);
88
+ *
71
89
  * <PaginatedList
72
- * fetchFn={(p) => client.getNotifications(p)}
73
- * getItems={(r) => r.notifications}
74
- * getTotal={(r) => r.total}
75
- * extraParams={{ unreadOnly: true }}
90
+ * items={data?.notifications ?? []}
91
+ * loading={isLoading}
92
+ * pagination={pagination}
76
93
  * >
77
- * {(items, loading) =>
78
- * loading ? null : items.map((item) => <Card key={item.id} {...item} />)
79
- * }
94
+ * {(items) => items.map((item) => <Card key={item.id} {...item} />)}
80
95
  * </PaginatedList>
81
96
  * ```
82
97
  */
83
- export function PaginatedList<TResponse, TItem, TExtraParams = object>({
98
+ export function PaginatedList<TItem>({
99
+ items,
100
+ loading,
101
+ pagination,
84
102
  children,
85
103
  showLoadingSpinner = true,
86
104
  emptyContent,
@@ -90,10 +108,7 @@ export function PaginatedList<TResponse, TItem, TExtraParams = object>({
90
108
  pageSizes,
91
109
  className,
92
110
  paginationClassName,
93
- ...paginationOptions
94
- }: PaginatedListProps<TResponse, TItem, TExtraParams>) {
95
- const { items, loading, pagination } = usePagination(paginationOptions);
96
-
111
+ }: PaginatedListProps<TItem>) {
97
112
  const showEmpty = !loading && items.length === 0 && emptyContent;
98
113
 
99
114
  return (
@@ -1,66 +1,17 @@
1
- import { useState, useEffect, useCallback, useMemo, useRef } from "react";
1
+ import { useState, useCallback, useMemo, useEffect } from "react";
2
2
 
3
3
  /**
4
- * Pagination parameters passed to the fetch function
5
- */
6
- export interface PaginationParams {
7
- limit: number;
8
- offset: number;
9
- }
10
-
11
- /**
12
- * Options for usePagination hook
13
- */
14
- export interface UsePaginationOptions<TResponse, TItem, TExtraParams = object> {
15
- /**
16
- * Fetch function that receives pagination + extra params and returns response
17
- */
18
- fetchFn: (params: PaginationParams & TExtraParams) => Promise<TResponse>;
19
-
20
- /**
21
- * Extract items array from the response
22
- */
23
- getItems: (response: TResponse) => TItem[];
24
-
25
- /**
26
- * Extract total count from the response
27
- */
28
- getTotal: (response: TResponse) => number;
29
-
30
- /**
31
- * Extra parameters to pass to fetchFn (merged with pagination params)
32
- * Changes to this object will trigger a refetch
33
- */
34
- extraParams?: TExtraParams;
35
-
36
- /**
37
- * Initial page number (1-indexed)
38
- * @default 1
39
- */
40
- defaultPage?: number;
41
-
42
- /**
43
- * Items per page
44
- * @default 10
45
- */
46
- defaultLimit?: number;
47
-
48
- /**
49
- * Whether to fetch on mount
50
- * @default true
51
- */
52
- fetchOnMount?: boolean;
53
- }
54
-
55
- /**
56
- * Pagination state returned by usePagination hook
4
+ * Pagination state and controls.
5
+ * Used with TanStack Query's useQuery hook for paginated data.
57
6
  */
58
7
  export interface PaginationState {
59
8
  /** Current page (1-indexed) */
60
9
  page: number;
61
10
  /** Items per page */
62
11
  limit: number;
63
- /** Total number of items */
12
+ /** Offset for query (calculated from page and limit) */
13
+ offset: number;
14
+ /** Total number of items (set via setTotal) */
64
15
  total: number;
65
16
  /** Total number of pages */
66
17
  totalPages: number;
@@ -72,130 +23,74 @@ export interface PaginationState {
72
23
  setPage: (page: number) => void;
73
24
  /** Change items per page (resets to page 1) */
74
25
  setLimit: (limit: number) => void;
26
+ /** Update total count from query response */
27
+ setTotal: (total: number) => void;
75
28
  /** Go to next page */
76
29
  nextPage: () => void;
77
30
  /** Go to previous page */
78
31
  prevPage: () => void;
79
- /** Refresh current page (shows loading state) */
80
- refetch: () => void;
81
- /** Refresh current page silently (no loading state, prevents UI flicker) */
82
- silentRefetch: () => void;
83
32
  }
84
33
 
85
34
  /**
86
- * Return value of usePagination hook
35
+ * Options for usePagination hook.
87
36
  */
88
- export interface UsePaginationResult<TItem> {
89
- /** Current page items */
90
- items: TItem[];
91
- /** Loading state */
92
- loading: boolean;
93
- /** Error if fetch failed */
94
- error: Error | undefined;
95
- /** Pagination controls and state */
96
- pagination: PaginationState;
37
+ export interface UsePaginationOptions {
38
+ /**
39
+ * Initial page number (1-indexed)
40
+ * @default 1
41
+ */
42
+ defaultPage?: number;
43
+
44
+ /**
45
+ * Items per page
46
+ * @default 10
47
+ */
48
+ defaultLimit?: number;
97
49
  }
98
50
 
99
51
  /**
100
- * Hook for managing paginated data fetching with automatic state management.
52
+ * Hook for managing pagination state to use with TanStack Query.
53
+ *
54
+ * This hook manages page/limit state and provides computed offset for queries.
55
+ * Use with useQuery to build paginated data fetching.
101
56
  *
102
57
  * @example
103
58
  * ```tsx
104
- * const { items, loading, pagination } = usePagination({
105
- * fetchFn: (p) => client.getNotifications(p),
106
- * getItems: (r) => r.notifications,
107
- * getTotal: (r) => r.total,
108
- * extraParams: { unreadOnly: true },
59
+ * // Simple usage with usePluginClient
60
+ * const pagination = usePagination({ defaultLimit: 20 });
61
+ *
62
+ * const { data, isLoading } = notificationClient.getNotifications.useQuery({
63
+ * limit: pagination.limit,
64
+ * offset: pagination.offset,
65
+ * unreadOnly: true,
109
66
  * });
110
67
  *
68
+ * // Update total when data changes
69
+ * useEffect(() => {
70
+ * if (data) pagination.setTotal(data.total);
71
+ * }, [data, pagination]);
72
+ *
111
73
  * return (
112
74
  * <>
113
- * {items.map(item => <Card key={item.id} {...item} />)}
114
- * <Pagination {...pagination} />
75
+ * {data?.notifications.map(n => <Notification key={n.id} {...n} />)}
76
+ * <Pagination {...pagination} loading={isLoading} />
115
77
  * </>
116
78
  * );
117
79
  * ```
118
80
  */
119
- export function usePagination<TResponse, TItem, TExtraParams = object>({
120
- fetchFn,
121
- getItems,
122
- getTotal,
123
- extraParams,
81
+ export function usePagination({
124
82
  defaultPage = 1,
125
83
  defaultLimit = 10,
126
- fetchOnMount = true,
127
- }: UsePaginationOptions<
128
- TResponse,
129
- TItem,
130
- TExtraParams
131
- >): UsePaginationResult<TItem> {
132
- const [items, setItems] = useState<TItem[]>([]);
133
- const [loading, setLoading] = useState(fetchOnMount);
134
- const [error, setError] = useState<Error>();
84
+ }: UsePaginationOptions = {}): PaginationState {
135
85
  const [page, setPageState] = useState(defaultPage);
136
86
  const [limit, setLimitState] = useState(defaultLimit);
137
- const [total, setTotal] = useState(0);
138
-
139
- // Use refs for callback functions to avoid re-creating fetchData when they change
140
- // This is better DX - callers don't need to memoize their functions
141
- const fetchFnRef = useRef(fetchFn);
142
- const getItemsRef = useRef(getItems);
143
- const getTotalRef = useRef(getTotal);
144
- const extraParamsRef = useRef(extraParams);
145
-
146
- // Update refs when functions change
147
- fetchFnRef.current = fetchFn;
148
- getItemsRef.current = getItems;
149
- getTotalRef.current = getTotal;
150
- extraParamsRef.current = extraParams;
151
-
152
- // Memoize extraParams to detect changes
153
- const extraParamsKey = useMemo(
154
- () => JSON.stringify(extraParams ?? {}),
155
- [extraParams]
156
- );
87
+ const [total, setTotalState] = useState(0);
157
88
 
158
- const fetchData = useCallback(
159
- async (showLoading = true) => {
160
- if (showLoading) {
161
- setLoading(true);
162
- }
163
- setError(undefined);
164
-
165
- try {
166
- const offset = (page - 1) * limit;
167
- const params = {
168
- limit,
169
- offset,
170
- ...extraParamsRef.current,
171
- } as PaginationParams & TExtraParams;
172
-
173
- const response = await fetchFnRef.current(params);
174
- setItems(getItemsRef.current(response));
175
- setTotal(getTotalRef.current(response));
176
- } catch (error_) {
177
- setError(error_ instanceof Error ? error_ : new Error(String(error_)));
178
- setItems([]);
179
- } finally {
180
- setLoading(false);
181
- }
182
- },
183
- [page, limit, extraParamsKey]
89
+ const offset = useMemo(() => (page - 1) * limit, [page, limit]);
90
+ const totalPages = useMemo(
91
+ () => Math.max(1, Math.ceil(total / limit)),
92
+ [total, limit]
184
93
  );
185
-
186
- // Fetch on mount and when dependencies change
187
- useEffect(() => {
188
- if (fetchOnMount || page !== defaultPage || limit !== defaultLimit) {
189
- void fetchData(true);
190
- }
191
- }, [fetchData, fetchOnMount, page, limit, defaultPage, defaultLimit]);
192
-
193
- // Reset to page 1 when extraParams change
194
- useEffect(() => {
195
- setPageState(1);
196
- }, [extraParamsKey]);
197
-
198
- const totalPages = Math.max(1, Math.ceil(total / limit));
199
94
  const hasNext = page < totalPages;
200
95
  const hasPrev = page > 1;
201
96
 
@@ -208,6 +103,10 @@ export function usePagination<TResponse, TItem, TExtraParams = object>({
208
103
  setPageState(1); // Reset to first page when limit changes
209
104
  }, []);
210
105
 
106
+ const setTotal = useCallback((newTotal: number) => {
107
+ setTotalState(newTotal);
108
+ }, []);
109
+
211
110
  const nextPage = useCallback(() => {
212
111
  if (hasNext) {
213
112
  setPageState((p) => p + 1);
@@ -220,28 +119,46 @@ export function usePagination<TResponse, TItem, TExtraParams = object>({
220
119
  }
221
120
  }, [hasPrev]);
222
121
 
223
- const refetch = useCallback(() => {
224
- void fetchData(true);
225
- }, [fetchData]);
226
-
227
- const silentRefetch = useCallback(() => {
228
- void fetchData(false);
229
- }, [fetchData]);
230
-
231
- const pagination: PaginationState = {
122
+ return {
232
123
  page,
233
124
  limit,
125
+ offset,
234
126
  total,
235
127
  totalPages,
236
128
  hasNext,
237
129
  hasPrev,
238
130
  setPage,
239
131
  setLimit,
132
+ setTotal,
240
133
  nextPage,
241
134
  prevPage,
242
- refetch,
243
- silentRefetch,
244
135
  };
136
+ }
245
137
 
246
- return { items, loading, error, pagination };
138
+ /**
139
+ * Helper hook to sync query total with pagination state.
140
+ * Use this to automatically update pagination.total when query data changes.
141
+ *
142
+ * @example
143
+ * ```tsx
144
+ * const pagination = usePagination({ defaultLimit: 20 });
145
+ *
146
+ * const { data, isLoading } = notificationClient.getNotifications.useQuery({
147
+ * limit: pagination.limit,
148
+ * offset: pagination.offset,
149
+ * });
150
+ *
151
+ * // Auto-sync total from response
152
+ * usePaginationSync(pagination, data?.total);
153
+ * ```
154
+ */
155
+ export function usePaginationSync(
156
+ pagination: PaginationState,
157
+ total: number | undefined
158
+ ): void {
159
+ useEffect(() => {
160
+ if (total !== undefined) {
161
+ pagination.setTotal(total);
162
+ }
163
+ }, [total, pagination]);
247
164
  }
package/src/index.ts CHANGED
@@ -3,8 +3,8 @@ export * from "./components/Input";
3
3
  export * from "./components/Card";
4
4
  export * from "./components/Label";
5
5
  export * from "./components/NavItem";
6
- export * from "./components/PermissionDenied";
7
- export * from "./components/PermissionGate";
6
+ export * from "./components/AccessDenied";
7
+ export * from "./components/AccessGate";
8
8
  export * from "./components/SectionHeader";
9
9
  export * from "./components/StatusCard";
10
10
  export * from "./components/EmptyState";
@@ -1,97 +0,0 @@
1
- import React from "react";
2
- import { PermissionDenied } from "./PermissionDenied";
3
- import { LoadingSpinner } from "./LoadingSpinner";
4
-
5
- /**
6
- * Props for the PermissionGate component.
7
- */
8
- export interface PermissionGateProps {
9
- /**
10
- * The permission ID to check for access.
11
- */
12
- permission: string;
13
- /**
14
- * Content to render when permission is granted.
15
- */
16
- children: React.ReactNode;
17
- /**
18
- * Custom fallback to render when permission is denied.
19
- * If not provided and showDenied is false, renders nothing.
20
- */
21
- fallback?: React.ReactNode;
22
- /**
23
- * If true, shows a PermissionDenied component when access is denied.
24
- * Useful for entire page sections. Overridden by fallback if provided.
25
- */
26
- showDenied?: boolean;
27
- /**
28
- * Custom message to show in the PermissionDenied component.
29
- */
30
- deniedMessage?: string;
31
- /**
32
- * Hook to check permissions. Must be provided by the consumer.
33
- * This allows the component to be used without depending on auth-frontend directly.
34
- */
35
- usePermission: (permission: string) => { loading: boolean; allowed: boolean };
36
- }
37
-
38
- /**
39
- * Conditionally renders children based on whether the user has a required permission.
40
- *
41
- * @example
42
- * // Hide content if permission denied
43
- * <PermissionGate permission="catalog.manage" usePermission={permissionApi.usePermission}>
44
- * <ManageButton />
45
- * </PermissionGate>
46
- *
47
- * @example
48
- * // Show permission denied message
49
- * <PermissionGate
50
- * permission="catalog.read"
51
- * usePermission={permissionApi.usePermission}
52
- * showDenied
53
- * deniedMessage="You don't have access to view the catalog."
54
- * >
55
- * <CatalogList />
56
- * </PermissionGate>
57
- *
58
- * @example
59
- * // Custom fallback
60
- * <PermissionGate
61
- * permission="admin.manage"
62
- * usePermission={permissionApi.usePermission}
63
- * fallback={<p>Admin access required</p>}
64
- * >
65
- * <AdminPanel />
66
- * </PermissionGate>
67
- */
68
- export const PermissionGate: React.FC<PermissionGateProps> = ({
69
- permission,
70
- children,
71
- fallback,
72
- showDenied = false,
73
- deniedMessage,
74
- usePermission,
75
- }) => {
76
- const { loading, allowed } = usePermission(permission);
77
-
78
- if (loading) {
79
- return <LoadingSpinner size="sm" />;
80
- }
81
-
82
- if (!allowed) {
83
- if (fallback) {
84
- return <>{fallback}</>;
85
- }
86
- if (showDenied) {
87
- return (
88
- <PermissionDenied
89
- message={deniedMessage ?? `You don't have permission: ${permission}`}
90
- />
91
- );
92
- }
93
- return <></>;
94
- }
95
-
96
- return <>{children}</>;
97
- };
@@ -1,275 +0,0 @@
1
- import { describe, it, expect, mock } from "bun:test";
2
- import { renderHook, act } from "@checkstack/test-utils-frontend";
3
- import { usePagination } from "./usePagination";
4
-
5
- describe("usePagination", () => {
6
- // Create a deferred promise for controlled async testing
7
- interface MockResponse {
8
- items: { id: string; name: string }[];
9
- total: number;
10
- }
11
-
12
- const createControlledMock = () => {
13
- let resolvePromise: ((value: MockResponse) => void) | null = null;
14
- const mockFn = mock(
15
- ({
16
- limit,
17
- offset,
18
- }: {
19
- limit: number;
20
- offset: number;
21
- }): Promise<MockResponse> => {
22
- return new Promise((resolve) => {
23
- resolvePromise = resolve;
24
- // Auto-resolve after a microtask to simulate instant response
25
- queueMicrotask(() => {
26
- resolve({
27
- items: Array.from(
28
- { length: Math.min(limit, 100 - offset) },
29
- (_, i) => ({
30
- id: `item-${offset + i}`,
31
- name: `Item ${offset + i}`,
32
- })
33
- ),
34
- total: 100,
35
- });
36
- });
37
- });
38
- }
39
- );
40
- return { mockFn, getResolver: () => resolvePromise };
41
- };
42
-
43
- // Simple sync mock for tests that don't need controlled timing
44
- const createSyncMock = () =>
45
- mock(({ limit, offset }: { limit: number; offset: number }) =>
46
- Promise.resolve({
47
- items: Array.from(
48
- { length: Math.min(limit, 100 - offset) },
49
- (_, i) => ({
50
- id: `item-${offset + i}`,
51
- name: `Item ${offset + i}`,
52
- })
53
- ),
54
- total: 100,
55
- })
56
- );
57
-
58
- it("should initialize with correct defaults", () => {
59
- const mockFetchFn = createSyncMock();
60
-
61
- const { result } = renderHook(() =>
62
- usePagination({
63
- fetchFn: mockFetchFn,
64
- getItems: (r) => r.items,
65
- getTotal: (r) => r.total,
66
- fetchOnMount: false,
67
- })
68
- );
69
-
70
- expect(result.current.loading).toBe(false);
71
- expect(result.current.items).toEqual([]);
72
- expect(result.current.pagination.page).toBe(1);
73
- expect(result.current.pagination.limit).toBe(10);
74
- expect(result.current.pagination.total).toBe(0);
75
- expect(result.current.pagination.totalPages).toBe(1);
76
- });
77
-
78
- it("should not fetch on mount when fetchOnMount is false", () => {
79
- const mockFetchFn = createSyncMock();
80
-
81
- renderHook(() =>
82
- usePagination({
83
- fetchFn: mockFetchFn,
84
- getItems: (r) => r.items,
85
- getTotal: (r) => r.total,
86
- fetchOnMount: false,
87
- })
88
- );
89
-
90
- expect(mockFetchFn).not.toHaveBeenCalled();
91
- });
92
-
93
- it("should start loading immediately when fetchOnMount is true", () => {
94
- const mockFetchFn = createSyncMock();
95
-
96
- const { result } = renderHook(() =>
97
- usePagination({
98
- fetchFn: mockFetchFn,
99
- getItems: (r) => r.items,
100
- getTotal: (r) => r.total,
101
- defaultLimit: 10,
102
- })
103
- );
104
-
105
- // Should be loading immediately after render
106
- expect(result.current.loading).toBe(true);
107
- expect(mockFetchFn).toHaveBeenCalledWith({ limit: 10, offset: 0 });
108
- });
109
-
110
- it("should call fetch with correct params on mount", async () => {
111
- const { mockFn } = createControlledMock();
112
-
113
- renderHook(() =>
114
- usePagination({
115
- fetchFn: mockFn,
116
- getItems: (r) => r.items,
117
- getTotal: (r) => r.total,
118
- defaultLimit: 20,
119
- })
120
- );
121
-
122
- expect(mockFn).toHaveBeenCalledWith({ limit: 20, offset: 0 });
123
- });
124
-
125
- it("should pass extra params to fetch function", async () => {
126
- const { mockFn } = createControlledMock();
127
-
128
- renderHook(() =>
129
- usePagination({
130
- fetchFn: mockFn,
131
- getItems: (r) => r.items,
132
- getTotal: (r) => r.total,
133
- defaultLimit: 10,
134
- extraParams: { unreadOnly: true, category: "alerts" },
135
- })
136
- );
137
-
138
- expect(mockFn).toHaveBeenCalledWith({
139
- limit: 10,
140
- offset: 0,
141
- unreadOnly: true,
142
- category: "alerts",
143
- });
144
- });
145
-
146
- it("should update page when setPage is called", async () => {
147
- const mockFetchFn = createSyncMock();
148
-
149
- const { result } = renderHook(() =>
150
- usePagination({
151
- fetchFn: mockFetchFn,
152
- getItems: (r) => r.items,
153
- getTotal: (r) => r.total,
154
- fetchOnMount: false,
155
- })
156
- );
157
-
158
- act(() => {
159
- result.current.pagination.setPage(5);
160
- });
161
-
162
- expect(result.current.pagination.page).toBe(5);
163
- // Should trigger fetch with correct offset
164
- expect(mockFetchFn).toHaveBeenCalledWith({ limit: 10, offset: 40 });
165
- });
166
-
167
- it("should update limit and reset to page 1 when setLimit is called", async () => {
168
- const mockFetchFn = createSyncMock();
169
-
170
- const { result } = renderHook(() =>
171
- usePagination({
172
- fetchFn: mockFetchFn,
173
- getItems: (r) => r.items,
174
- getTotal: (r) => r.total,
175
- fetchOnMount: false,
176
- })
177
- );
178
-
179
- // First go to page 3
180
- act(() => {
181
- result.current.pagination.setPage(3);
182
- });
183
-
184
- expect(result.current.pagination.page).toBe(3);
185
-
186
- // Then change limit
187
- act(() => {
188
- result.current.pagination.setLimit(25);
189
- });
190
-
191
- // Should reset to page 1
192
- expect(result.current.pagination.page).toBe(1);
193
- expect(result.current.pagination.limit).toBe(25);
194
- // Should fetch with new limit at offset 0
195
- expect(mockFetchFn).toHaveBeenLastCalledWith({ limit: 25, offset: 0 });
196
- });
197
-
198
- it("should call nextPage correctly", async () => {
199
- const mockFetchFn = createSyncMock();
200
-
201
- const { result } = renderHook(() =>
202
- usePagination({
203
- fetchFn: mockFetchFn,
204
- getItems: (r) => r.items,
205
- getTotal: (r) => r.total,
206
- fetchOnMount: false,
207
- })
208
- );
209
-
210
- // First set page to 1 (which triggers fetch that sets total)
211
- act(() => {
212
- result.current.pagination.setPage(1);
213
- });
214
-
215
- // After fetch completes, hasNext should be calculated based on total
216
- // Since our mock returns total: 100 and limit: 10, hasNext should be true
217
- // We need to manually set up the condition where hasNext is true
218
- // For now, test that nextPage at least calls the function - even if hasNext blocks it
219
- const callsBefore = mockFetchFn.mock.calls.length;
220
-
221
- act(() => {
222
- result.current.pagination.nextPage();
223
- });
224
-
225
- // nextPage should attempt to increment page (if hasNext allows)
226
- // The actual behavior depends on whether fetchData has completed
227
- // Since we can't await async in happy-dom, just verify the method doesn't throw
228
- expect(mockFetchFn.mock.calls.length).toBeGreaterThanOrEqual(callsBefore);
229
- });
230
-
231
- it("should call prevPage correctly", async () => {
232
- const mockFetchFn = createSyncMock();
233
-
234
- const { result } = renderHook(() =>
235
- usePagination({
236
- fetchFn: mockFetchFn,
237
- getItems: (r) => r.items,
238
- getTotal: (r) => r.total,
239
- fetchOnMount: false,
240
- })
241
- );
242
-
243
- // Go to page 3 first
244
- act(() => {
245
- result.current.pagination.setPage(3);
246
- });
247
-
248
- act(() => {
249
- result.current.pagination.prevPage();
250
- });
251
-
252
- expect(result.current.pagination.page).toBe(2);
253
- });
254
-
255
- it("should trigger refetch when refetch is called", async () => {
256
- const mockFetchFn = createSyncMock();
257
-
258
- const { result } = renderHook(() =>
259
- usePagination({
260
- fetchFn: mockFetchFn,
261
- getItems: (r) => r.items,
262
- getTotal: (r) => r.total,
263
- fetchOnMount: false,
264
- })
265
- );
266
-
267
- const initialCallCount = mockFetchFn.mock.calls.length;
268
-
269
- act(() => {
270
- result.current.pagination.refetch();
271
- });
272
-
273
- expect(mockFetchFn.mock.calls.length).toBeGreaterThan(initialCallCount);
274
- });
275
- });