-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy pathObjectCalendar.tsx
More file actions
433 lines (383 loc) · 13.7 KB
/
ObjectCalendar.tsx
File metadata and controls
433 lines (383 loc) · 13.7 KB
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
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
/**
* ObjectUI
* Copyright (c) 2024-present ObjectStack Inc.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/
/**
* ObjectCalendar Component
*
* A specialized calendar component that works with ObjectQL data sources.
* Displays records as calendar events based on date field configuration.
* Implements the calendar view type from @objectstack/spec view.zod ListView schema.
*
* Features:
* - Month/week/day calendar views
* - Auto-mapping of records to calendar events
* - Date range filtering
* - Event click handling
* - Color coding support
* - Works with object/api/value data providers
*/
import React, { useEffect, useState, useCallback, useMemo, useRef } from 'react';
import type { ObjectGridSchema, DataSource, ViewData, CalendarConfig } from '@object-ui/types';
import { CalendarView, type CalendarEvent } from './CalendarView';
import { usePullToRefresh } from '@object-ui/mobile';
import { useNavigationOverlay } from '@object-ui/react';
import { NavigationOverlay } from '@object-ui/components';
import { extractRecords, buildExpandFields } from '@object-ui/core';
export interface CalendarSchema {
type: 'calendar';
objectName?: string;
dateField?: string;
endField?: string;
titleField?: string;
colorField?: string;
filter?: any;
sort?: any;
/** Initial view mode */
defaultView?: 'month' | 'week' | 'day';
}
export interface ObjectCalendarProps {
schema: ObjectGridSchema | CalendarSchema;
dataSource?: DataSource;
className?: string;
/** Pre-fetched records passed by a parent (e.g. ObjectView). When provided, skips internal data fetching. */
data?: any[];
/** Loading state propagated from a parent. Respected only when `data` is also provided. */
loading?: boolean;
onEventClick?: (record: any) => void;
onRowClick?: (record: any) => void;
onDateClick?: (date: Date) => void;
onEdit?: (record: any) => void;
onDelete?: (record: any) => void;
onNavigate?: (date: Date) => void;
onViewChange?: (view: 'month' | 'week' | 'day') => void;
onEventDrop?: (record: any, newStart: Date, newEnd?: Date) => void;
locale?: string;
}
/**
* Helper to get data configuration from schema
*/
function getDataConfig(schema: ObjectGridSchema | CalendarSchema): ViewData | null {
if ('data' in schema && schema.data) {
return schema.data;
}
if ('staticData' in schema && schema.staticData) {
return {
provider: 'value',
items: schema.staticData,
};
}
if (schema.objectName) {
return {
provider: 'object',
object: schema.objectName,
};
}
return null;
}
/**
* Helper to convert sort config to QueryParams format
*/
function convertSortToQueryParams(sort: string | any[] | undefined): Record<string, 'asc' | 'desc'> | undefined {
if (!sort) return undefined;
// If it's a string like "name desc"
if (typeof sort === 'string') {
const parts = sort.split(' ');
const field = parts[0];
const order = (parts[1]?.toLowerCase() === 'desc' ? 'desc' : 'asc') as 'asc' | 'desc';
return { [field]: order };
}
// If it's an array of SortConfig objects
if (Array.isArray(sort)) {
return sort.reduce((acc, item) => {
if (item.field && item.order) {
acc[item.field] = item.order;
}
return acc;
}, {} as Record<string, 'asc' | 'desc'>);
}
return undefined;
}
/**
* Helper to get calendar configuration from schema
*/
function getCalendarConfig(schema: ObjectGridSchema | CalendarSchema): CalendarConfig | null {
// Check if schema has calendar configuration
if ('filter' in schema && schema.filter && typeof schema.filter === 'object' && 'calendar' in schema.filter) {
return (schema.filter as any).calendar as CalendarConfig;
}
// For backward compatibility, check if schema has calendar config at root
if ((schema as any).calendar) {
return (schema as any).calendar as CalendarConfig;
}
// Check for flat properties (used by ObjectView)
if ((schema as any).startDateField || (schema as any).dateField) {
return {
startDateField: (schema as any).startDateField || (schema as any).dateField,
endDateField: (schema as any).endDateField || (schema as any).endField,
titleField: (schema as any).titleField || 'name',
colorField: (schema as any).colorField,
allDayField: (schema as any).allDayField
} as CalendarConfig;
}
return null;
}
export const ObjectCalendar: React.FC<ObjectCalendarProps> = ({
schema,
dataSource,
className,
data: externalData,
loading: externalLoading,
onEventClick,
onRowClick,
onDateClick,
onNavigate,
onViewChange,
onEventDrop,
locale,
}) => {
// When the parent (e.g. ObjectView) pre-fetches data and passes it via the `data` prop,
// we must not trigger a second fetch. Detect external data by checking for an array.
const hasExternalData = Array.isArray(externalData);
const [data, setData] = useState<any[]>(hasExternalData ? externalData! : []);
const [loading, setLoading] = useState(hasExternalData ? (externalLoading ?? false) : true);
const [error, setError] = useState<Error | null>(null);
const [objectSchema, setObjectSchema] = useState<any>(null);
const [currentDate, setCurrentDate] = useState(new Date());
const [view, setView] = useState<'month' | 'week' | 'day'>('month');
const [refreshKey, setRefreshKey] = useState(0);
// P2: Auto-subscribe to DataSource mutation events (standalone mode only).
// When rendered as a child of ObjectView with external data, parent handles refresh.
useEffect(() => {
if (hasExternalData) return; // Parent handles refresh
if (!dataSource?.onMutation || !schema.objectName) return;
const unsub = dataSource.onMutation((event: any) => {
if (event.resource === schema.objectName) {
setRefreshKey(k => k + 1);
}
});
return unsub;
}, [dataSource, schema.objectName, hasExternalData]);
const handlePullRefresh = useCallback(async () => {
setRefreshKey(k => k + 1);
}, []);
const { ref: pullRef, isRefreshing, pullDistance } = usePullToRefresh<HTMLDivElement>({
onRefresh: handlePullRefresh,
enabled: !!dataSource && !!schema.objectName,
});
const dataConfig = useMemo(() => getDataConfig(schema), [
(schema as any).data,
(schema as any).staticData,
schema.objectName,
]);
const calendarConfig = useMemo(() => getCalendarConfig(schema), [
schema.filter,
(schema as any).calendar,
(schema as any).dateField,
(schema as any).endField,
(schema as any).titleField,
(schema as any).colorField
]);
const hasInlineData = dataConfig?.provider === 'value';
// Use ref for objectSchema to avoid double-fetch on mount
const objectSchemaRef = useRef<any>(null);
objectSchemaRef.current = objectSchema;
// Sync external data/loading changes from parent (e.g. ObjectView re-fetches after filter change)
useEffect(() => {
if (hasExternalData) {
setData(externalData!);
}
}, [externalData, hasExternalData]);
useEffect(() => {
if (hasExternalData && externalLoading !== undefined) {
setLoading(externalLoading);
}
}, [externalLoading, hasExternalData]);
// Fetch data based on provider
useEffect(() => {
// Skip internal fetch when data is managed by a parent component
if (hasExternalData) return;
let isMounted = true;
const fetchData = async () => {
try {
if (!isMounted) return;
setLoading(true);
if (hasInlineData && dataConfig?.provider === 'value') {
if (isMounted) {
setData(dataConfig.items as any[]);
setLoading(false);
}
return;
}
if (!dataSource || typeof dataSource.find !== 'function') {
throw new Error('DataSource required for object/api providers');
}
if (dataConfig?.provider === 'object') {
const objectName = dataConfig.object;
// Auto-inject $expand for lookup/master_detail fields
const expand = buildExpandFields(objectSchemaRef.current?.fields);
const result = await dataSource.find(objectName, {
$filter: schema.filter,
$orderby: convertSortToQueryParams(schema.sort),
...(expand.length > 0 ? { $expand: expand } : {}),
});
let items: any[] = extractRecords(result);
if (isMounted) {
setData(items);
}
} else if (dataConfig?.provider === 'api') {
console.warn('API provider not yet implemented for ObjectCalendar');
if (isMounted) setData([]);
}
if (isMounted) setLoading(false);
} catch (err) {
console.error('[ObjectCalendar] Error fetching data:', err);
if (isMounted) {
setError(err as Error);
setLoading(false);
}
}
};
fetchData();
return () => { isMounted = false; };
}, [hasExternalData, dataConfig, dataSource, hasInlineData, schema.filter, schema.sort, refreshKey]);
// Fetch object schema for field metadata
useEffect(() => {
const fetchObjectSchema = async () => {
try {
if (!dataSource) return;
const objectName = dataConfig?.provider === 'object'
? dataConfig.object
: schema.objectName;
if (!objectName) return;
const schemaData = await dataSource.getObjectSchema(objectName);
setObjectSchema(schemaData);
} catch (err) {
console.error('Failed to fetch object schema:', err);
}
};
if (!hasInlineData && dataSource) {
fetchObjectSchema();
}
}, [schema.objectName, dataSource, hasInlineData, dataConfig]);
// Transform data to calendar events
const events = useMemo(() => {
if (!calendarConfig || !data.length) {
return [];
}
const { startDateField, endDateField, titleField, colorField } = calendarConfig;
return data.map((record, index) => {
const startDate = record[startDateField];
const endDate = endDateField ? record[endDateField] : null;
const title = record[titleField] || 'Untitled';
const color = colorField ? record[colorField] : undefined;
return {
id: record.id || record._id || `event-${index}`,
title,
start: startDate ? new Date(startDate) : new Date(),
end: endDate ? new Date(endDate) : undefined,
color,
allDay: !endDate, // If no end date, treat as all-day event
data: record,
};
}).filter(event => !isNaN(event.start.getTime())); // Filter out invalid dates
}, [data, calendarConfig]);
// Get days in current month view - REMOVED (Handled by CalendarView)
const handleCreate = useCallback(() => {
// Standard "Create" action trigger
const today = new Date();
onDateClick?.(today);
}, [onDateClick]);
// --- NavigationConfig support ---
// Must be called before any early returns to satisfy React hooks rules
const navigation = useNavigationOverlay({
navigation: (schema as any).navigation,
objectName: schema.objectName,
onRowClick,
});
if (loading) {
return (
<div className={className}>
<div className="flex items-center justify-center h-96">
<div className="text-muted-foreground">Loading calendar...</div>
</div>
</div>
);
}
if (error) {
return (
<div className={className}>
<div className="flex items-center justify-center h-96">
<div className="text-destructive">Error: {error.message}</div>
</div>
</div>
);
}
if (!calendarConfig) {
return (
<div className={className}>
<div className="flex items-center justify-center h-96">
<div className="text-muted-foreground">
Calendar configuration required. Please specify startDateField and titleField.
</div>
</div>
</div>
);
}
return (
<div ref={pullRef} className={className}>
{pullDistance > 0 && (
<div
className="flex items-center justify-center text-xs text-muted-foreground"
style={{ height: pullDistance }}
>
{isRefreshing ? 'Refreshing…' : 'Pull to refresh'}
</div>
)}
<div className="border rounded-lg bg-background h-[calc(100vh-120px)] sm:h-[calc(100vh-160px)] md:h-[calc(100vh-200px)] min-h-[400px] sm:min-h-[600px]">
<CalendarView
events={events}
currentDate={currentDate}
view={(schema as any).defaultView || 'month'}
locale={locale}
onEventClick={(event) => {
navigation.handleClick(event.data);
onEventClick?.(event.data);
}}
onDateClick={onDateClick}
onNavigate={(date) => {
setCurrentDate(date);
onNavigate?.(date);
}}
onViewChange={(v) => {
setView(v);
onViewChange?.(v);
}}
onAddClick={undefined}
onEventDrop={onEventDrop ? (event, newStart, newEnd) => {
onEventDrop(event.data, newStart, newEnd);
} : undefined}
/>
</div>
{navigation.isOverlay && (
<NavigationOverlay {...navigation} title="Event Details">
{(record) => (
<div className="space-y-3">
{Object.entries(record).map(([key, value]) => (
<div key={key} className="flex flex-col">
<span className="text-xs font-medium text-muted-foreground uppercase tracking-wide">
{key.replace(/_/g, ' ')}
</span>
<span className="text-sm">{String(value ?? '—')}</span>
</div>
))}
</div>
)}
</NavigationOverlay>
)}
</div>
);
};