@objectstack/client-react 4.0.4 → 4.1.0

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.
@@ -1,314 +0,0 @@
1
- // Copyright (c) 2025 ObjectStack. Licensed under the Apache-2.0 license.
2
-
3
- /**
4
- * Metadata Hooks
5
- *
6
- * React hooks for accessing ObjectStack metadata (schemas, views, fields)
7
- */
8
-
9
- import { useState, useEffect, useCallback } from 'react';
10
- import { useClient } from './context';
11
-
12
- /**
13
- * Metadata query options
14
- */
15
- export interface UseMetadataOptions {
16
- /** Enable/disable automatic query execution */
17
- enabled?: boolean;
18
- /** Use cached metadata if available */
19
- useCache?: boolean;
20
- /** ETag for conditional requests */
21
- ifNoneMatch?: string;
22
- /** If-Modified-Since header for conditional requests */
23
- ifModifiedSince?: string;
24
- /** Callback on successful query */
25
- onSuccess?: (data: any) => void;
26
- /** Callback on error */
27
- onError?: (error: Error) => void;
28
- }
29
-
30
- /**
31
- * Metadata query result
32
- */
33
- export interface UseMetadataResult<T = any> {
34
- /** Metadata data */
35
- data: T | null;
36
- /** Loading state */
37
- isLoading: boolean;
38
- /** Error state */
39
- error: Error | null;
40
- /** Refetch the metadata */
41
- refetch: () => Promise<void>;
42
- /** ETag from last fetch */
43
- etag?: string;
44
- /** Whether data came from cache (304 Not Modified) */
45
- fromCache: boolean;
46
- }
47
-
48
- /**
49
- * Hook for fetching object schema/metadata
50
- *
51
- * @example
52
- * ```tsx
53
- * function ObjectSchemaViewer({ objectName }: { objectName: string }) {
54
- * const { data: schema, isLoading, error } = useObject(objectName);
55
- *
56
- * if (isLoading) return <div>Loading schema...</div>;
57
- * if (error) return <div>Error: {error.message}</div>;
58
- *
59
- * return (
60
- * <div>
61
- * <h2>{schema.label}</h2>
62
- * <p>Fields: {Object.keys(schema.fields).length}</p>
63
- * </div>
64
- * );
65
- * }
66
- * ```
67
- */
68
- export function useObject(
69
- objectName: string,
70
- options: UseMetadataOptions = {}
71
- ): UseMetadataResult {
72
- const client = useClient();
73
- const [data, setData] = useState<any>(null);
74
- const [isLoading, setIsLoading] = useState(true);
75
- const [error, setError] = useState<Error | null>(null);
76
- const [etag, setEtag] = useState<string>();
77
- const [fromCache, setFromCache] = useState(false);
78
-
79
- const {
80
- enabled = true,
81
- useCache = true,
82
- ifNoneMatch,
83
- ifModifiedSince,
84
- onSuccess,
85
- onError
86
- } = options;
87
-
88
- const fetchMetadata = useCallback(async () => {
89
- if (!enabled) return;
90
-
91
- try {
92
- setIsLoading(true);
93
- setError(null);
94
- setFromCache(false);
95
-
96
- if (useCache) {
97
- // Use cached metadata endpoint
98
- const result = await client.meta.getCached(objectName, {
99
- ifNoneMatch: ifNoneMatch || etag,
100
- ifModifiedSince
101
- });
102
-
103
- if (result.notModified) {
104
- setFromCache(true);
105
- } else {
106
- setData(result.data);
107
- if (result.etag) {
108
- setEtag(result.etag.value);
109
- }
110
- }
111
-
112
- onSuccess?.(result.data || data);
113
- } else {
114
- // Direct fetch without cache
115
- const result = await client.meta.getItem('object', objectName);
116
- setData(result);
117
- onSuccess?.(result);
118
- }
119
- } catch (err) {
120
- const error = err instanceof Error ? err : new Error('Failed to fetch object metadata');
121
- setError(error);
122
- onError?.(error);
123
- } finally {
124
- setIsLoading(false);
125
- }
126
- }, [client, objectName, enabled, useCache, ifNoneMatch, ifModifiedSince, etag, data, onSuccess, onError]);
127
-
128
- useEffect(() => {
129
- fetchMetadata();
130
- }, [fetchMetadata]);
131
-
132
- const refetch = useCallback(async () => {
133
- await fetchMetadata();
134
- }, [fetchMetadata]);
135
-
136
- return {
137
- data,
138
- isLoading,
139
- error,
140
- refetch,
141
- etag,
142
- fromCache
143
- };
144
- }
145
-
146
- /**
147
- * Hook for fetching view configuration
148
- *
149
- * @example
150
- * ```tsx
151
- * function ViewConfiguration({ objectName }: { objectName: string }) {
152
- * const { data: view, isLoading } = useView(objectName, 'list');
153
- *
154
- * if (isLoading) return <div>Loading view...</div>;
155
- *
156
- * return (
157
- * <div>
158
- * <h3>List View for {objectName}</h3>
159
- * <p>Columns: {view?.columns?.length}</p>
160
- * </div>
161
- * );
162
- * }
163
- * ```
164
- */
165
- export function useView(
166
- objectName: string,
167
- viewType: 'list' | 'form' = 'list',
168
- options: UseMetadataOptions = {}
169
- ): UseMetadataResult {
170
- const client = useClient();
171
- const [data, setData] = useState<any>(null);
172
- const [isLoading, setIsLoading] = useState(true);
173
- const [error, setError] = useState<Error | null>(null);
174
-
175
- const { enabled = true, onSuccess, onError } = options;
176
-
177
- const fetchView = useCallback(async () => {
178
- if (!enabled) return;
179
-
180
- try {
181
- setIsLoading(true);
182
- setError(null);
183
-
184
- const result = await client.meta.getView(objectName, viewType);
185
- setData(result);
186
- onSuccess?.(result);
187
- } catch (err) {
188
- const error = err instanceof Error ? err : new Error('Failed to fetch view configuration');
189
- setError(error);
190
- onError?.(error);
191
- } finally {
192
- setIsLoading(false);
193
- }
194
- }, [client, objectName, viewType, enabled, onSuccess, onError]);
195
-
196
- useEffect(() => {
197
- fetchView();
198
- }, [fetchView]);
199
-
200
- const refetch = useCallback(async () => {
201
- await fetchView();
202
- }, [fetchView]);
203
-
204
- return {
205
- data,
206
- isLoading,
207
- error,
208
- refetch,
209
- fromCache: false
210
- };
211
- }
212
-
213
- /**
214
- * Hook for extracting fields from object schema
215
- *
216
- * @example
217
- * ```tsx
218
- * function FieldList({ objectName }: { objectName: string }) {
219
- * const { data: fields, isLoading } = useFields(objectName);
220
- *
221
- * if (isLoading) return <div>Loading fields...</div>;
222
- *
223
- * return (
224
- * <ul>
225
- * {fields?.map(field => (
226
- * <li key={field.name}>{field.label} ({field.type})</li>
227
- * ))}
228
- * </ul>
229
- * );
230
- * }
231
- * ```
232
- */
233
- export function useFields(
234
- objectName: string,
235
- options: UseMetadataOptions = {}
236
- ): UseMetadataResult<any[]> {
237
- const objectResult = useObject(objectName, options);
238
-
239
- const fields = objectResult.data?.fields
240
- ? Object.entries(objectResult.data.fields).map(([name, field]: [string, any]) => ({
241
- name,
242
- ...field
243
- }))
244
- : null;
245
-
246
- return {
247
- ...objectResult,
248
- data: fields
249
- };
250
- }
251
-
252
- /**
253
- * Generic metadata hook for custom metadata queries
254
- *
255
- * @example
256
- * ```tsx
257
- * function CustomMetadata() {
258
- * const { data, isLoading } = useMetadata(async (client) => {
259
- * // Custom metadata fetching logic
260
- * const object = await client.meta.getObject('custom_object');
261
- * const view = await client.meta.getView('custom_object', 'list');
262
- * return { object, view };
263
- * });
264
- *
265
- * return <pre>{JSON.stringify(data, null, 2)}</pre>;
266
- * }
267
- * ```
268
- */
269
- export function useMetadata<T = any>(
270
- fetcher: (client: ReturnType<typeof useClient>) => Promise<T>,
271
- options: Omit<UseMetadataOptions, 'useCache' | 'ifNoneMatch' | 'ifModifiedSince'> = {}
272
- ): UseMetadataResult<T> {
273
- const client = useClient();
274
- const [data, setData] = useState<T | null>(null);
275
- const [isLoading, setIsLoading] = useState(true);
276
- const [error, setError] = useState<Error | null>(null);
277
-
278
- const { enabled = true, onSuccess, onError } = options;
279
-
280
- const fetchMetadata = useCallback(async () => {
281
- if (!enabled) return;
282
-
283
- try {
284
- setIsLoading(true);
285
- setError(null);
286
-
287
- const result = await fetcher(client);
288
- setData(result);
289
- onSuccess?.(result);
290
- } catch (err) {
291
- const error = err instanceof Error ? err : new Error('Failed to fetch metadata');
292
- setError(error);
293
- onError?.(error);
294
- } finally {
295
- setIsLoading(false);
296
- }
297
- }, [client, fetcher, enabled, onSuccess, onError]);
298
-
299
- useEffect(() => {
300
- fetchMetadata();
301
- }, [fetchMetadata]);
302
-
303
- const refetch = useCallback(async () => {
304
- await fetchMetadata();
305
- }, [fetchMetadata]);
306
-
307
- return {
308
- data,
309
- isLoading,
310
- error,
311
- refetch,
312
- fromCache: false
313
- };
314
- }
@@ -1,262 +0,0 @@
1
- // Copyright (c) 2025 ObjectStack. Licensed under the Apache-2.0 license.
2
-
3
- /**
4
- * Real-time Event Subscription Hooks
5
- *
6
- * Provides React hooks for subscribing to metadata and data events.
7
- * Events are automatically cleaned up when components unmount.
8
- */
9
-
10
- import { useEffect, useState, useCallback } from 'react';
11
- import type { MetadataEvent, DataEvent } from '@objectstack/spec/api';
12
- import { useClient } from './context';
13
-
14
- /**
15
- * Hook to subscribe to metadata events
16
- *
17
- * @param type - Metadata type to subscribe to (e.g., 'object', 'view', 'agent')
18
- * @param options - Optional filters (packageId)
19
- * @returns Latest metadata event or null
20
- *
21
- * @example
22
- * ```tsx
23
- * function ObjectList() {
24
- * const event = useMetadataSubscription('object');
25
- *
26
- * useEffect(() => {
27
- * if (event?.type === 'metadata.object.created') {
28
- * console.log('New object:', event.name);
29
- * // Refresh list
30
- * }
31
- * }, [event]);
32
- *
33
- * return <div>...</div>;
34
- * }
35
- * ```
36
- */
37
- export function useMetadataSubscription(
38
- type: string,
39
- options?: { packageId?: string }
40
- ): MetadataEvent | null {
41
- const client = useClient();
42
- const [event, setEvent] = useState<MetadataEvent | null>(null);
43
-
44
- useEffect(() => {
45
- if (!client) return;
46
-
47
- const unsubscribe = client.events.subscribeMetadata(
48
- type,
49
- (e) => setEvent(e),
50
- options
51
- );
52
-
53
- return () => {
54
- unsubscribe();
55
- };
56
- }, [client, type, options?.packageId]);
57
-
58
- return event;
59
- }
60
-
61
- /**
62
- * Hook to subscribe to data record events
63
- *
64
- * @param object - Object name to subscribe to
65
- * @param options - Optional filters (recordId for specific record)
66
- * @returns Latest data event or null
67
- *
68
- * @example
69
- * ```tsx
70
- * function TaskDetail({ taskId }: { taskId: string }) {
71
- * const event = useDataSubscription('project_task', { recordId: taskId });
72
- *
73
- * useEffect(() => {
74
- * if (event?.type === 'data.record.updated') {
75
- * console.log('Task updated:', event.changes);
76
- * // Refresh task data
77
- * }
78
- * }, [event]);
79
- *
80
- * return <div>...</div>;
81
- * }
82
- * ```
83
- */
84
- export function useDataSubscription(
85
- object: string,
86
- options?: { recordId?: string }
87
- ): DataEvent | null {
88
- const client = useClient();
89
- const [event, setEvent] = useState<DataEvent | null>(null);
90
-
91
- useEffect(() => {
92
- if (!client) return;
93
-
94
- const unsubscribe = client.events.subscribeData(
95
- object,
96
- (e) => setEvent(e),
97
- options
98
- );
99
-
100
- return () => {
101
- unsubscribe();
102
- };
103
- }, [client, object, options?.recordId]);
104
-
105
- return event;
106
- }
107
-
108
- /**
109
- * Hook to subscribe to metadata events with a callback
110
- *
111
- * This variant doesn't store events in state, it just triggers a callback.
112
- * Useful for triggering refetches or side effects without re-renders.
113
- *
114
- * @param type - Metadata type to subscribe to
115
- * @param callback - Callback to invoke on events
116
- * @param options - Optional filters
117
- *
118
- * @example
119
- * ```tsx
120
- * function ObjectList() {
121
- * const { refetch } = useQuery(...);
122
- *
123
- * useMetadataSubscriptionCallback('object', () => {
124
- * refetch(); // Refetch list when objects change
125
- * });
126
- *
127
- * return <div>...</div>;
128
- * }
129
- * ```
130
- */
131
- export function useMetadataSubscriptionCallback(
132
- type: string,
133
- callback: (event: MetadataEvent) => void,
134
- options?: { packageId?: string }
135
- ): void {
136
- const client = useClient();
137
-
138
- useEffect(() => {
139
- if (!client) return;
140
-
141
- const unsubscribe = client.events.subscribeMetadata(
142
- type,
143
- callback,
144
- options
145
- );
146
-
147
- return () => {
148
- unsubscribe();
149
- };
150
- }, [client, type, callback, options?.packageId]);
151
- }
152
-
153
- /**
154
- * Hook to subscribe to data events with a callback
155
- *
156
- * @param object - Object name to subscribe to
157
- * @param callback - Callback to invoke on events
158
- * @param options - Optional filters
159
- *
160
- * @example
161
- * ```tsx
162
- * function TaskList() {
163
- * const { refetch } = useQuery(...);
164
- *
165
- * useDataSubscriptionCallback('project_task', () => {
166
- * refetch(); // Refetch list when tasks change
167
- * });
168
- *
169
- * return <div>...</div>;
170
- * }
171
- * ```
172
- */
173
- export function useDataSubscriptionCallback(
174
- object: string,
175
- callback: (event: DataEvent) => void,
176
- options?: { recordId?: string }
177
- ): void {
178
- const client = useClient();
179
-
180
- useEffect(() => {
181
- if (!client) return;
182
-
183
- const unsubscribe = client.events.subscribeData(
184
- object,
185
- callback,
186
- options
187
- );
188
-
189
- return () => {
190
- unsubscribe();
191
- };
192
- }, [client, object, callback, options?.recordId]);
193
- }
194
-
195
- /**
196
- * Hook to get connection status of realtime events
197
- *
198
- * @returns Whether realtime is connected
199
- *
200
- * @example
201
- * ```tsx
202
- * function ConnectionIndicator() {
203
- * const connected = useRealtimeConnection();
204
- *
205
- * return (
206
- * <div>
207
- * {connected ? '🟢 Connected' : '🔴 Disconnected'}
208
- * </div>
209
- * );
210
- * }
211
- * ```
212
- */
213
- export function useRealtimeConnection(): boolean {
214
- const client = useClient();
215
- const [connected, setConnected] = useState(true);
216
-
217
- useEffect(() => {
218
- if (!client) {
219
- setConnected(false);
220
- return;
221
- }
222
-
223
- // For now, assume always connected with in-memory adapter
224
- // In production, this would listen to WebSocket connection events
225
- setConnected(true);
226
- }, [client]);
227
-
228
- return connected;
229
- }
230
-
231
- /**
232
- * Hook for auto-refreshing queries when data changes
233
- *
234
- * Combines data subscription with query refetch.
235
- *
236
- * @param object - Object name to watch
237
- * @param refetch - Refetch function from useQuery
238
- * @param options - Optional filters
239
- *
240
- * @example
241
- * ```tsx
242
- * function TaskList() {
243
- * const { data, refetch } = useQuery('project_task', {});
244
- *
245
- * useAutoRefresh('project_task', refetch);
246
- *
247
- * return <div>{data.map(...)}</div>;
248
- * }
249
- * ```
250
- */
251
- export function useAutoRefresh(
252
- object: string,
253
- refetch: () => void,
254
- options?: { recordId?: string }
255
- ): void {
256
- const handleEvent = useCallback((_event: DataEvent) => {
257
- // Refetch on any data change
258
- refetch();
259
- }, [refetch]);
260
-
261
- useDataSubscriptionCallback(object, handleEvent, options);
262
- }
package/tsconfig.json DELETED
@@ -1,14 +0,0 @@
1
- {
2
- "extends": "../../tsconfig.json",
3
- "compilerOptions": {
4
- "outDir": "./dist",
5
- "rootDir": "./src",
6
- "declaration": true,
7
- "declarationMap": true,
8
- "jsx": "react",
9
- "lib": ["ES2020", "DOM", "DOM.Iterable"],
10
- "types": ["node", "react"]
11
- },
12
- "include": ["src/**/*"],
13
- "exclude": ["node_modules", "dist", "**/*.test.ts"]
14
- }