-
Notifications
You must be signed in to change notification settings - Fork 5
Expand file tree
/
Copy pathDetailSection.tsx
More file actions
340 lines (317 loc) · 12.7 KB
/
Copy pathDetailSection.tsx
File metadata and controls
340 lines (317 loc) · 12.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
/**
* 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 * as React from 'react';
import {
cn,
Card,
CardHeader,
CardTitle,
CardContent,
Collapsible,
CollapsibleTrigger,
CollapsibleContent,
Badge,
Button,
Tooltip,
TooltipContent,
TooltipProvider,
TooltipTrigger,
} from '@object-ui/components';
import { ChevronDown, ChevronRight, Copy, Check } from 'lucide-react';
import { SchemaRenderer } from '@object-ui/react';
import { getCellRenderer } from '@object-ui/fields';
import type { DetailViewSection as DetailViewSectionType, DetailViewField, FieldMetadata } from '@object-ui/types';
import { applyDetailAutoLayout } from './autoLayout';
import { useDetailTranslation } from './useDetailTranslation';
import { useSafeFieldLabel } from '@object-ui/react';
/**
* Compute responsive col-span classes so that col-span never exceeds the
* visible column count at each Tailwind breakpoint.
*
* For columns=1: no span class (always single column)
* For columns=2: md:col-span-{min(span,2)}
* For columns>=3: md:col-span-{min(span,2)} lg:col-span-{min(span,3)}
*/
export function getResponsiveSpanClass(span: number | undefined, columns: number): string {
if (!span || span <= 1 || columns <= 1) return '';
if (columns === 2) {
return span >= 2 ? 'md:col-span-2' : '';
}
// columns >= 3: grid-cols-1 md:grid-cols-2 lg:grid-cols-3
if (span === 2) return 'md:col-span-2';
if (span >= 3) return 'md:col-span-2 lg:col-span-3';
return '';
}
export interface VirtualScrollOptions {
/** Enable virtual scrolling for large field sets */
enabled?: boolean;
/** Height of each field row in px (default: 60) */
itemHeight?: number;
/** Number of fields to render in the initial batch before revealing all (default: 20) */
batchSize?: number;
}
export interface DetailSectionProps {
section: DetailViewSectionType;
data?: any;
className?: string;
/** Object schema from DataSource for field type enrichment */
objectSchema?: any;
/** Object name for i18n field label resolution */
objectName?: string;
/** Whether inline editing is active */
isEditing?: boolean;
/** Callback when a field value changes during inline editing */
onFieldChange?: (field: string, value: any) => void;
/** Virtual scrolling configuration for sections with many fields */
virtualScroll?: VirtualScrollOptions;
}
export const DetailSection: React.FC<DetailSectionProps> = ({
section,
data,
className,
objectSchema,
objectName,
isEditing = false,
onFieldChange,
virtualScroll,
}) => {
const [isCollapsed, setIsCollapsed] = React.useState(section.defaultCollapsed ?? false);
const [copiedField, setCopiedField] = React.useState<string | null>(null);
const [visibleCount, setVisibleCount] = React.useState<number | undefined>(undefined);
const { t } = useDetailTranslation();
const { fieldLabel } = useSafeFieldLabel();
const handleCopyField = React.useCallback((fieldName: string, value: any) => {
const textValue = value !== null && value !== undefined ? String(value) : '';
navigator.clipboard.writeText(textValue).then(() => {
setCopiedField(fieldName);
setTimeout(() => setCopiedField(null), 2000);
});
}, []);
// Filter out empty fields when hideEmpty is set
const visibleFields = section.hideEmpty
? section.fields.filter((field) => {
const value = data?.[field.name] ?? field.value;
return value !== null && value !== undefined && value !== '';
})
: section.fields;
// Hide entire section when all fields are empty
if (visibleFields.length === 0) return null;
// Apply auto-layout: infer columns and auto-span wide fields
const { fields: layoutFields, columns: effectiveColumns } = applyDetailAutoLayout(
visibleFields,
section.columns
);
const renderField = (field: DetailViewField) => {
const value = data?.[field.name] ?? field.value;
// If custom renderer provided
if (field.render) {
return <SchemaRenderer schema={field.render} data={{ ...data, value }} />;
}
// Calculate responsive span class so col-span never exceeds the visible
// column count at each breakpoint, preventing implicit columns on mobile.
const spanClass = getResponsiveSpanClass(field.span, effectiveColumns);
const displayValue = (() => {
if (value === null || value === undefined) return <span className="text-muted-foreground/50 text-xs italic">—</span>;
// Enrich field with objectSchema metadata — merge missing properties
// even when field.type is explicitly set (e.g., type: 'lookup' without reference_to)
const objectDefField = objectSchema?.fields?.[field.name];
const resolvedType = field.type || objectDefField?.type;
const enrichedField: Record<string, any> = { ...field };
if (objectDefField) {
if (!field.type && objectDefField.type) enrichedField.type = objectDefField.type;
if (objectDefField.options && !enrichedField.options) enrichedField.options = objectDefField.options;
if (objectDefField.currency && !enrichedField.currency) enrichedField.currency = objectDefField.currency;
if (objectDefField.precision !== undefined && enrichedField.precision === undefined) enrichedField.precision = objectDefField.precision;
if (objectDefField.format && !enrichedField.format) enrichedField.format = objectDefField.format;
const refTarget = objectDefField.reference_to || objectDefField.reference;
if (refTarget && !enrichedField.reference_to) enrichedField.reference_to = refTarget;
if (objectDefField.reference_field && !enrichedField.reference_field) enrichedField.reference_field = objectDefField.reference_field;
}
// Use type-aware cell renderer when field type is available (explicit or enriched)
if (resolvedType) {
const CellRenderer = getCellRenderer(resolvedType);
if (CellRenderer) {
return <CellRenderer value={value} field={enrichedField as unknown as FieldMetadata} />;
}
}
return String(value);
})();
const canCopy = value !== null && value !== undefined && value !== '';
const isCopied = copiedField === field.name;
// Default field rendering with copy button and touch-friendly targets
return (
<div key={field.name} className={cn("space-y-1.5 group", spanClass)}>
<div className="text-xs font-medium text-muted-foreground uppercase tracking-wide">
{fieldLabel(objectName || '', field.name, field.label || field.name)}
</div>
{isEditing && !field.readonly ? (
<div className="min-h-[44px] sm:min-h-0">
<input
type={field.type === 'number' ? 'number' : field.type === 'date' ? 'date' : 'text'}
className="w-full px-2 py-1.5 text-sm border rounded-md bg-background focus:outline-none focus:ring-2 focus:ring-ring"
value={value != null ? String(value) : ''}
onChange={(e) => onFieldChange?.(field.name, e.target.value)}
/>
</div>
) : (
<div
className={cn(
"flex items-start justify-between gap-2 min-h-[44px] sm:min-h-0 rounded-md",
canCopy && "cursor-pointer active:bg-muted/60 transition-colors"
)}
onClick={canCopy ? () => handleCopyField(field.name, value) : undefined}
onKeyDown={canCopy ? (e: React.KeyboardEvent) => {
if (e.key === 'Enter' || e.key === ' ') {
e.preventDefault();
handleCopyField(field.name, value);
}
} : undefined}
role={canCopy ? "button" : undefined}
tabIndex={canCopy ? 0 : undefined}
>
<div className="text-sm flex-1 break-words py-1">
{displayValue}
</div>
{canCopy && (
<TooltipProvider>
<Tooltip>
<TooltipTrigger asChild>
<Button
variant="ghost"
size="icon"
className="h-6 w-6 opacity-0 group-hover:opacity-100 transition-opacity shrink-0"
onClick={(e) => {
e.stopPropagation();
handleCopyField(field.name, value);
}}
>
{isCopied ? (
<Check className="h-3 w-3 text-green-600" />
) : (
<Copy className="h-3 w-3" />
)}
</Button>
</TooltipTrigger>
<TooltipContent>
{isCopied ? t('detail.copied') : t('detail.copyToClipboard')}
</TooltipContent>
</Tooltip>
</TooltipProvider>
)}
</div>
)}
</div>
);
};
// Virtual scroll: progressive batch rendering for large field sets
const vsEnabled = virtualScroll?.enabled === true;
const vsBatchSize = virtualScroll?.batchSize ?? 20;
/** Delay (ms) before revealing remaining fields after the initial batch */
const VS_REVEAL_DELAY = 100;
React.useEffect(() => {
if (!vsEnabled) {
setVisibleCount(undefined);
return;
}
// Start with a batch, then progressively reveal more
if (layoutFields.length <= vsBatchSize) {
setVisibleCount(undefined);
return;
}
setVisibleCount(vsBatchSize);
const timer = setTimeout(() => setVisibleCount(undefined), VS_REVEAL_DELAY);
return () => clearTimeout(timer);
// eslint-disable-next-line react-hooks/exhaustive-deps
}, [vsEnabled, layoutFields.length, vsBatchSize]);
const renderedFields = visibleCount !== undefined
? layoutFields.slice(0, visibleCount)
: layoutFields;
const content = (
<div
className={cn(
"grid gap-3 sm:gap-4",
effectiveColumns === 1 ? "grid-cols-1" :
effectiveColumns === 2 ? "grid-cols-1 md:grid-cols-2" :
effectiveColumns === 3 ? "grid-cols-1 md:grid-cols-2 lg:grid-cols-3" :
"grid-cols-1 md:grid-cols-2 lg:grid-cols-3"
)}
>
{renderedFields.map(renderField)}
</div>
);
if (!section.collapsible) {
return (
<Card className={cn(section.showBorder === false ? 'border-none shadow-none' : '', className)}>
{section.title && (
<CardHeader className={cn(section.headerColor && `bg-${section.headerColor}`)}>
<CardTitle className="flex items-center justify-between">
<div className="flex items-center gap-2">
{section.icon && <span className="text-muted-foreground">{section.icon}</span>}
<span>{section.title}</span>
{section.fields && (
<Badge variant="secondary" className="ml-2 text-xs">
{section.fields.length}
</Badge>
)}
</div>
</CardTitle>
{section.description && (
<p className="text-sm text-muted-foreground mt-1.5">{section.description}</p>
)}
</CardHeader>
)}
<CardContent className="pt-4 sm:pt-6 px-3 sm:px-6">
{content}
</CardContent>
</Card>
);
}
return (
<Collapsible
open={!isCollapsed}
onOpenChange={(open) => setIsCollapsed(!open)}
className={className}
>
<Card>
<CollapsibleTrigger asChild>
<CardHeader className={cn(
"cursor-pointer hover:bg-muted/50 transition-colors",
section.headerColor && `bg-${section.headerColor}`
)}>
<CardTitle className="flex items-center justify-between">
<div className="flex items-center gap-2">
{section.icon && <span className="text-muted-foreground">{section.icon}</span>}
<span>{section.title}</span>
{section.fields && (
<Badge variant="secondary" className="ml-2 text-xs">
{section.fields.length}
</Badge>
)}
</div>
<div className="flex items-center gap-2">
{isCollapsed ? (
<ChevronRight className="h-4 w-4 text-muted-foreground" />
) : (
<ChevronDown className="h-4 w-4 text-muted-foreground" />
)}
</div>
</CardTitle>
{section.description && !isCollapsed && (
<p className="text-sm text-muted-foreground mt-1.5">{section.description}</p>
)}
</CardHeader>
</CollapsibleTrigger>
<CollapsibleContent>
<CardContent className="pt-4 sm:pt-6 px-3 sm:px-6">
{content}
</CardContent>
</CollapsibleContent>
</Card>
</Collapsible>
);
};