-
Notifications
You must be signed in to change notification settings - Fork 3
Expand file tree
/
Copy pathObjectKanban.tsx
More file actions
276 lines (245 loc) · 9.67 KB
/
ObjectKanban.tsx
File metadata and controls
276 lines (245 loc) · 9.67 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
/**
* 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.
*/
import React, { useEffect, useState, useMemo } from 'react';
import type { DataSource } from '@object-ui/types';
import { useDataScope, useNavigationOverlay } from '@object-ui/react';
import { NavigationOverlay } from '@object-ui/components';
import { extractRecords, buildExpandFields } from '@object-ui/core';
import { KanbanRenderer } from './index';
import { KanbanSchema } from './types';
export interface ObjectKanbanProps {
schema: KanbanSchema;
dataSource?: DataSource;
className?: string; // Allow override
/** Pre-fetched records passed by a parent (e.g. ListView). When provided, skips internal data fetching. */
data?: any[];
/** Loading state propagated from a parent. Respected only when `data` is also provided. */
loading?: boolean;
onRowClick?: (record: any) => void;
onCardClick?: (record: any) => void;
}
export const ObjectKanban: React.FC<ObjectKanbanProps> = ({
schema,
dataSource,
className,
data: externalData,
loading: externalLoading,
onRowClick,
onCardClick,
..._props
}) => {
// When a parent (e.g. ListView) pre-fetches data and passes it via the `data` prop,
// we must not trigger a second fetch. Detect external data by checking if externalData
// is an array (undefined when not provided by parent).
const hasExternalData = Array.isArray(externalData);
const [fetchedData, setFetchedData] = useState<any[]>([]);
const [objectDef, setObjectDef] = useState<any>(null);
// loading state
const [loading, setLoading] = useState(hasExternalData ? (externalLoading ?? false) : false);
const [error, setError] = useState<Error | null>(null);
const [refreshKey, setRefreshKey] = useState(0);
// Resolve bound data if 'bind' property exists
const boundData = useDataScope(schema.bind);
// P2: Auto-subscribe to DataSource mutation events (standalone mode only).
// When rendered as a child of ListView, data is managed externally and this is skipped.
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]);
// Sync external data changes from parent (e.g. ListView re-fetches after filter change)
useEffect(() => {
if (hasExternalData && externalLoading !== undefined) {
setLoading(externalLoading);
}
}, [externalLoading, hasExternalData]);
// Fetch object definition for metadata (labels, options)
useEffect(() => {
let isMounted = true;
const fetchMeta = async () => {
if (!dataSource || !schema.objectName) return;
try {
const def = await dataSource.getObjectSchema(schema.objectName);
if (isMounted) setObjectDef(def);
} catch (e) {
console.warn("Failed to fetch object def", e);
}
};
fetchMeta();
return () => { isMounted = false; };
}, [schema.objectName, dataSource]);
useEffect(() => {
// Skip internal fetch when data is managed by a parent component
if (hasExternalData) return;
let isMounted = true;
const fetchData = async () => {
if (!dataSource || typeof dataSource.find !== 'function' || !schema.objectName) return;
if (isMounted) setLoading(true);
try {
// Auto-inject $expand for lookup/master_detail fields
const expand = buildExpandFields(objectDef?.fields);
const results = await dataSource.find(schema.objectName, {
options: { $top: 100 },
$filter: schema.filter,
...(expand.length > 0 ? { $expand: expand } : {}),
});
// Handle { value: [] } OData shape or { data: [] } shape or direct array
const data = extractRecords(results);
if (isMounted) {
setFetchedData(data);
}
} catch (e) {
console.error('[ObjectKanban] Fetch error:', e);
if (isMounted) setError(e as Error);
} finally {
if (isMounted) setLoading(false);
}
};
// Trigger fetch if we have an objectName AND verify no inline/bound data overrides it
if (schema.objectName && !boundData && !schema.data) {
fetchData();
}
return () => { isMounted = false; };
}, [schema.objectName, dataSource, boundData, schema.data, schema.filter, hasExternalData, objectDef, refreshKey]);
// Determine which data to use: external -> bound -> inline -> fetched
const rawData = (hasExternalData ? externalData : undefined) || boundData || schema.data || fetchedData;
// Enhance data with title mapping and ensure IDs
const effectiveData = useMemo(() => {
if (!Array.isArray(rawData)) return [];
// Support cardTitle property from schema (passed by ObjectView)
// Fallback to legacy titleField for backwards compatibility
let titleField = schema.cardTitle || (schema as any).titleField;
// Fallback: Try to infer from object definition
if (!titleField && objectDef) {
// 1. Check for titleFormat like "{subject}" first (Higher priority for Cards)
if (objectDef.titleFormat) {
const match = /\{(.+?)\}/.exec(objectDef.titleFormat);
if (match) titleField = match[1];
}
// 2. Check for standard NAME_FIELD_KEY
if (!titleField && objectDef.NAME_FIELD_KEY) {
titleField = objectDef.NAME_FIELD_KEY;
}
}
// Common title field names to try as fallback
const TITLE_FALLBACK_FIELDS = ['name', 'title', 'subject', 'label', 'display_name'];
return rawData.map(item => {
// If a specific title field was configured, try it first
let resolvedTitle = titleField ? item[titleField] : undefined;
// Fallback: try common field names
if (!resolvedTitle) {
for (const field of TITLE_FALLBACK_FIELDS) {
if (item[field]) {
resolvedTitle = item[field];
break;
}
}
}
return {
...item,
// Ensure id exists
id: item.id || item._id,
// Map title
title: resolvedTitle || 'Untitled',
};
});
}, [rawData, schema, objectDef]);
// Generate columns if missing but groupBy is present
const effectiveColumns = useMemo(() => {
// If columns exist, returns them (normalized)
if (schema.columns && schema.columns.length > 0) {
// If columns is array of strings, normalize to objects
if (typeof schema.columns[0] === 'string') {
// If grouping is active, assume string columns are meant for data display, not lanes
if (!schema.groupBy) {
return (schema.columns as unknown as string[]).map(val => ({
id: val,
title: val
}));
}
} else {
return schema.columns;
}
}
// Try to get options from metadata
if (schema.groupBy && objectDef?.fields?.[schema.groupBy]?.options) {
return objectDef.fields[schema.groupBy].options.map((opt: any) => ({
id: opt.value,
title: opt.label
}));
}
// If no columns, but we have groupBy and data, generate from data
if (schema.groupBy && effectiveData.length > 0) {
const groups = new Set(effectiveData.map(item => item[schema.groupBy!]));
return Array.from(groups).map(g => ({
id: String(g),
title: String(g)
}));
}
return [];
}, [schema.columns, schema.groupBy, effectiveData, objectDef]);
// Clone schema to inject data and className
// Use grouping.fields[0].field as swimlaneField fallback when no explicit swimlaneField
const effectiveSwimlaneField = schema.swimlaneField
|| (schema.grouping?.fields?.[0]?.field);
const effectiveSchema = {
...schema,
data: effectiveData,
columns: effectiveColumns,
className: className || schema.className,
...(effectiveSwimlaneField ? { swimlaneField: effectiveSwimlaneField } : {}),
};
const navigation = useNavigationOverlay({
navigation: (schema as any).navigation,
objectName: schema.objectName,
onRowClick: onRowClick ?? onCardClick,
});
if (error) {
return (
<div className="p-4 border border-destructive/50 rounded bg-destructive/10 text-destructive">
Error loading kanban data: {error.message}
</div>
);
}
// Pass through to the renderer
const detailTitle = schema.objectName
? `${schema.objectName.charAt(0).toUpperCase() + schema.objectName.slice(1).replace(/_/g, ' ')} Detail`
: 'Card Details';
return (
<>
<KanbanRenderer schema={{
...effectiveSchema,
onCardClick: (card: any) => {
navigation.handleClick(card);
onCardClick?.(card);
},
}} />
{navigation.isOverlay && (
<NavigationOverlay {...navigation} title={detailTitle}>
{(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>
)}
</>
);
}