-
Notifications
You must be signed in to change notification settings - Fork 5
Expand file tree
/
Copy pathrenderer.tsx
More file actions
625 lines (599 loc) · 20.8 KB
/
Copy pathrenderer.tsx
File metadata and controls
625 lines (599 loc) · 20.8 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
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
/**
* 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 { ComponentRegistry } from '@object-ui/core';
import type { TimelineSchema } from '@object-ui/types';
import {
Timeline,
TimelineItem,
TimelineMarker,
TimelineContent,
TimelineTitle,
TimelineTime,
TimelineDescription,
TimelineHorizontal,
TimelineHorizontalItem,
TimelineGantt,
TimelineGanttHeader,
TimelineGanttRowLabels,
TimelineGanttGrid,
TimelineGanttRow,
TimelineGanttLabel,
TimelineGanttBar,
TimelineGanttBarContent,
} from './index';
import { renderChildren, cn } from '@object-ui/components';
// Constants
/**
* The spec's timeline scale vocabulary (`ui/view.zod.ts`
* `TimelineConfigSchema.scale`). Exported for the spec-parity test.
*/
export const TIMELINE_SCALES: ReadonlySet<string> = new Set([
'hour', 'day', 'week', 'month', 'quarter', 'year',
]);
/**
* Resolve the axis scale for the gantt variant. The spec key is `scale`;
* `timeScale` is this renderer's pre-spec dialect, kept for stored JSON —
* before #2942 ONLY `timeScale` was read, so every spec-authored `scale`
* (all six values) was silently ignored. An absent/unknown value keeps the
* renderer's historical `month` default. The `vertical` / `horizontal`
* variants are sequential event feeds with no time axis, so `scale` has
* nothing to bucket there by construction.
*/
export function resolveTimelineScale(schema: { scale?: unknown; timeScale?: unknown }): string {
const raw = schema.scale ?? schema.timeScale;
return typeof raw === 'string' && TIMELINE_SCALES.has(raw) ? raw : 'month';
}
/**
* Gantt header labels for one scale across [minDate, maxDate]. Every spec
* scale produces a non-empty header row — `hour` / `quarter` / `year` used to
* fall through the month/week/day chain and return `[]`, blanking the axis
* (#2942). Exported for the spec-parity test.
*/
export function generateTimeScaleHeaders(scale: string, minDate: string, maxDate: string): string[] {
const headers: string[] = [];
const start = new Date(minDate);
const end = new Date(maxDate);
if (Number.isNaN(start.getTime()) || Number.isNaN(end.getTime()) || start > end) return headers;
const current = new Date(start);
switch (scale) {
case 'hour':
while (current <= end) {
headers.push(current.toLocaleString('en-US', { month: 'short', day: 'numeric', hour: 'numeric' }));
current.setHours(current.getHours() + 1);
}
break;
case 'day':
while (current <= end) {
headers.push(current.toLocaleDateString('en-US', { month: 'short', day: 'numeric' }));
current.setDate(current.getDate() + 1);
}
break;
case 'week': {
let week = 1;
while (current <= end) {
headers.push(`Week ${week++}`);
current.setDate(current.getDate() + 7);
}
break;
}
case 'quarter':
current.setMonth(Math.floor(current.getMonth() / 3) * 3, 1);
while (current <= end) {
headers.push(`Q${Math.floor(current.getMonth() / 3) + 1} ${current.getFullYear()}`);
current.setMonth(current.getMonth() + 3);
}
break;
case 'year':
// Snap to the calendar-year start so every year touched by the range
// gets a bucket (mirrors the quarter snap above).
current.setMonth(0, 1);
while (current <= end) {
headers.push(String(current.getFullYear()));
current.setFullYear(current.getFullYear() + 1);
}
break;
case 'month':
default:
while (current <= end) {
headers.push(current.toLocaleDateString('en-US', { month: 'short', year: 'numeric' }));
current.setMonth(current.getMonth() + 1);
}
break;
}
return headers;
}
// Helper function to calculate date range from items
function calculateDateRange(items: any[]): { minDate: string; maxDate: string } {
const allDates = items.flatMap((row: any) =>
(row.items || []).flatMap((item: any) => [item.startDate, item.endDate])
);
const minTimestamp = Math.min(...allDates.map((d: string) => new Date(d).getTime()));
const maxTimestamp = Math.max(...allDates.map((d: string) => new Date(d).getTime()));
return {
minDate: new Date(minTimestamp).toISOString().split('T')[0],
maxDate: new Date(maxTimestamp).toISOString().split('T')[0],
};
}
// Helper function to calculate bar position and width based on dates
function calculateBarDimensions(
startDate: string,
endDate: string,
minDate: string,
maxDate: string
): { start: number; width: number } {
const start = new Date(startDate).getTime();
const end = new Date(endDate).getTime();
const min = new Date(minDate).getTime();
const max = new Date(maxDate).getTime();
const totalDuration = max - min;
const startOffset = start - min;
const duration = end - start;
return {
start: (startOffset / totalDuration) * 100,
width: (duration / totalDuration) * 100,
};
}
// Helper function to format date
function formatDate(dateString: string, format?: string): string {
const date = new Date(dateString);
if (format === 'short') {
return date.toLocaleDateString();
}
if (format === 'long') {
return date.toLocaleDateString('en-US', {
year: 'numeric',
month: 'long',
day: 'numeric',
});
}
return date.toISOString().split('T')[0];
}
/**
* Render an inline option chip for the per-item metadata strip
* (status, priority, …). Uses the option color when supplied so the
* chip visually echoes the marker, falling back to a neutral pill
* when the option has no color metadata.
*/
function MetaChip({ label, color }: { label: string; color?: string }) {
const style = color
? { backgroundColor: `${color}22`, color, borderColor: `${color}55` }
: undefined;
return (
<span
className={cn(
'inline-flex items-center rounded-full border px-2 py-0.5 text-xs font-medium',
!color && 'bg-muted text-muted-foreground border-transparent'
)}
style={style}
>
{label}
</span>
);
}
/** Group adjacent items that share the same `group` key (already in
* display order) into a single section so the renderer can drop a
* sticky header above each bucket. */
function groupAdjacent<T extends { group?: string | null }>(items: T[]): Array<{ key: string; items: T[] }> {
const out: Array<{ key: string; items: T[] }> = [];
for (const it of items) {
const key = it.group == null ? '' : String(it.group);
const last = out[out.length - 1];
if (last && last.key === key) last.items.push(it);
else out.push({ key, items: [it] });
}
return out;
}
export const TimelineRenderer = ({ schema, className, ...props }: { schema: TimelineSchema; className?: string; [key: string]: any }) => {
const {
variant = 'vertical',
items = [],
dateFormat = 'short',
onItemClick,
} = schema;
// Vertical Timeline
if (variant === 'vertical') {
// Detect whether the data was annotated with a `group` key
// (ObjectTimeline does this for both explicit groupBy and the
// automatic date bucketing fallback). When present we render
// sticky bucket headers; when absent we keep the historical flat
// list so JSON-defined timelines aren't visually disturbed.
const groups = groupAdjacent(items as Array<any>);
const hasGroups = groups.some((g) => g.key !== '');
const renderItem = (item: any, key: React.Key) => {
// Custom CSS color from objectDef option metadata overrides the
// CVA variant — that lets the marker reflect the live status
// colour (e.g. amber for "in progress") without us hard-coding
// every status into the variants enum.
const markerStyle = item.color
? { backgroundColor: `${item.color}33`, borderColor: item.color }
: undefined;
const dateLabel = item.time
? formatDate(item.time, dateFormat)
: (item.startDate ? formatDate(item.startDate, dateFormat) : '');
const endLabel = item.endDate && item.endDate !== item.startDate
? formatDate(item.endDate, dateFormat)
: '';
const meta = Array.isArray(item.meta) ? item.meta : [];
return (
<TimelineItem
key={key}
density="compact"
className={cn(item.className, onItemClick && 'cursor-pointer')}
onClick={() => onItemClick?.(item)}
>
<TimelineMarker
variant={item.color ? 'default' : (item.variant || 'default')}
style={markerStyle}
>
{item.icon && <span className="text-xs">{item.icon}</span>}
</TimelineMarker>
<TimelineContent>
{(dateLabel || endLabel) && (
<TimelineTime
dateTime={item.time || item.startDate}
className="!mb-1 text-xs"
>
{dateLabel}
{endLabel && <span className="text-muted-foreground/70"> → {endLabel}</span>}
</TimelineTime>
)}
{item.title && <TimelineTitle className="text-sm sm:text-base mb-1">{item.title}</TimelineTitle>}
{meta.length > 0 && (
<div className="flex flex-wrap gap-1.5 mt-1 mb-1">
{meta.map((m: any) => (
<MetaChip key={m.key} label={m.label} color={m.color} />
))}
</div>
)}
{item.description && (
<TimelineDescription className="text-sm text-muted-foreground line-clamp-2 sm:line-clamp-none">
{item.description}
</TimelineDescription>
)}
{item.content && renderChildren(item.content)}
</TimelineContent>
</TimelineItem>
);
};
if (!hasGroups) {
return (
<Timeline className={className} {...props}>
{(items as Array<any>).map((item, index) => renderItem(item, index))}
</Timeline>
);
}
return (
<div className={cn('px-4 sm:px-6 py-2', className)} {...props}>
{groups.map((g, gi) => (
<section key={`${g.key}-${gi}`} className="mb-4">
<header className="sticky top-0 z-10 -mx-4 sm:-mx-6 px-4 sm:px-6 py-1.5 backdrop-blur bg-background/90 text-xs font-semibold uppercase tracking-wide text-muted-foreground border-b">
<span>{g.key}</span>
<span className="ml-2 text-muted-foreground/60 font-normal normal-case">
{g.items.length}
</span>
</header>
<Timeline className="mt-3">
{g.items.map((item, index) => renderItem(item, `${gi}-${index}`))}
</Timeline>
</section>
))}
</div>
);
}
// Horizontal Timeline
if (variant === 'horizontal') {
return (
<TimelineHorizontal className={cn("overflow-x-auto [-webkit-overflow-scrolling:touch]", className)} {...props}>
{items.map((item: any, index: number) => (
<TimelineHorizontalItem key={index} className={cn(item.className, onItemClick && 'cursor-pointer')} onClick={() => onItemClick?.(item)}>
<div className="flex flex-col items-center">
<TimelineMarker variant={item.variant || 'default'}>
{item.icon && <span className="text-xs">{item.icon}</span>}
</TimelineMarker>
<div className="mt-4 text-center">
{item.time && (
<TimelineTime dateTime={item.time}>
{formatDate(item.time, dateFormat)}
</TimelineTime>
)}
{item.title && <TimelineTitle>{item.title}</TimelineTitle>}
{item.description && (
<TimelineDescription className="text-center line-clamp-2 sm:line-clamp-none">
{item.description}
</TimelineDescription>
)}
{item.content && renderChildren(item.content)}
</div>
</div>
{index < items.length - 1 && (
<div className="absolute left-full w-16 border-t-2 border-gray-200 top-3" />
)}
</TimelineHorizontalItem>
))}
</TimelineHorizontal>
);
}
// Gantt/Airtable-style Timeline
if (variant === 'gantt') {
// Calculate date range from all items
const dateRange = calculateDateRange(items);
const minDate = schema.minDate || dateRange.minDate;
const maxDate = schema.maxDate || dateRange.maxDate;
// Generate time scale headers — the spec `scale` key drives this
// (legacy `timeScale` kept for stored JSON); every spec scale produces
// a header row (#2942).
const timeHeaders = generateTimeScaleHeaders(
resolveTimelineScale(schema as { scale?: unknown; timeScale?: unknown }),
minDate,
maxDate,
);
return (
<TimelineGantt className={cn("overflow-x-auto [-webkit-overflow-scrolling:touch]", className)} {...props}>
{/* Header */}
<TimelineGanttHeader>
<TimelineGanttRowLabels className="flex items-center px-2 sm:px-4 py-2 sm:py-3">
<span className="font-semibold text-xs sm:text-sm">
{schema.rowLabel || 'Items'}
</span>
</TimelineGanttRowLabels>
<TimelineGanttGrid>
<div className="flex h-full">
{timeHeaders.map((header, index) => (
<div
key={index}
className="flex-1 px-1 sm:px-2 py-2 sm:py-3 border-r text-xs font-medium text-center"
>
{header}
</div>
))}
</div>
</TimelineGanttGrid>
</TimelineGanttHeader>
{/* Rows */}
<div>
<div className="flex">
<TimelineGanttRowLabels>
{items.map((row: any, rowIndex: number) => (
<TimelineGanttRow key={rowIndex}>
<TimelineGanttLabel title={row.label} className="truncate">
{row.label}
</TimelineGanttLabel>
</TimelineGanttRow>
))}
</TimelineGanttRowLabels>
<TimelineGanttGrid className="relative">
{items.map((row: any, rowIndex: number) => (
<TimelineGanttRow key={rowIndex} className="relative">
{(row.items || []).map((item: any, itemIndex: number) => {
const dimensions = calculateBarDimensions(
item.startDate,
item.endDate,
minDate,
maxDate
);
return (
<TimelineGanttBar
key={itemIndex}
start={dimensions.start}
width={dimensions.width}
variant={item.variant || 'default'}
onClick={() => onItemClick?.(item, row, rowIndex, itemIndex)}
title={`${item.title || ''}\n${formatDate(item.startDate, dateFormat)} - ${formatDate(item.endDate, dateFormat)}`}
>
<TimelineGanttBarContent>
{item.title}
</TimelineGanttBarContent>
</TimelineGanttBar>
);
})}
</TimelineGanttRow>
))}
</TimelineGanttGrid>
</div>
</div>
</TimelineGantt>
);
}
return null;
};
ComponentRegistry.register(
'timeline',
TimelineRenderer,
{
namespace: 'plugin-timeline',
label: 'Timeline',
category: 'data-display',
inputs: [
{
name: 'variant',
type: 'enum',
enum: ['vertical', 'horizontal', 'gantt'],
label: 'Timeline Variant',
defaultValue: 'vertical',
},
{
name: 'items',
type: 'array',
label: 'Timeline Items',
description:
'For vertical/horizontal: Array of { time, title, description, variant, icon, content }. For gantt: Array of { label, items: [{ title, startDate, endDate, variant }] }',
},
{
name: 'dateFormat',
type: 'enum',
enum: ['short', 'long', 'iso'],
label: 'Date Format',
defaultValue: 'short',
},
{
name: 'timeScale',
type: 'enum',
enum: ['day', 'week', 'month'],
label: 'Time Scale (Gantt only)',
defaultValue: 'month',
},
{
name: 'rowLabel',
type: 'string',
label: 'Row Label (Gantt only)',
defaultValue: 'Items',
},
{
name: 'minDate',
type: 'string',
label: 'Min Date (Gantt only)',
description: 'Override auto-calculated min date (YYYY-MM-DD)',
},
{
name: 'maxDate',
type: 'string',
label: 'Max Date (Gantt only)',
description: 'Override auto-calculated max date (YYYY-MM-DD)',
},
{ name: 'className', type: 'string', label: 'CSS Class' },
],
defaultProps: {
variant: 'vertical',
dateFormat: 'short',
items: [
{
time: '2024-01-15',
title: 'Project Started',
description: 'Kickoff meeting and initial planning',
variant: 'success',
icon: '🚀',
},
{
time: '2024-02-01',
title: 'First Milestone',
description: 'Completed initial design phase',
variant: 'info',
icon: '🎨',
},
{
time: '2024-03-15',
title: 'Beta Release',
description: 'Released beta version to testers',
variant: 'warning',
icon: '⚡',
},
{
time: '2024-04-01',
title: 'Launch',
description: 'Official product launch',
variant: 'success',
icon: '🎉',
},
],
},
examples: {
vertical: {
variant: 'vertical',
dateFormat: 'long',
items: [
{
time: '2024-01-15',
title: 'Project Started',
description: 'Kickoff meeting and initial planning',
variant: 'success',
},
{
time: '2024-02-01',
title: 'First Milestone',
description: 'Completed initial design phase',
variant: 'info',
},
],
},
horizontal: {
variant: 'horizontal',
dateFormat: 'short',
items: [
{
time: '2024-01-01',
title: 'Q1',
description: 'First quarter',
variant: 'default',
},
{
time: '2024-04-01',
title: 'Q2',
description: 'Second quarter',
variant: 'info',
},
{
time: '2024-07-01',
title: 'Q3',
description: 'Third quarter',
variant: 'warning',
},
{
time: '2024-10-01',
title: 'Q4',
description: 'Fourth quarter',
variant: 'success',
},
],
},
gantt: {
variant: 'gantt',
dateFormat: 'short',
timeScale: 'month',
rowLabel: 'Projects',
items: [
{
label: 'Backend Development',
items: [
{
title: 'API Design',
startDate: '2024-01-01',
endDate: '2024-01-31',
variant: 'success',
},
{
title: 'Implementation',
startDate: '2024-02-01',
endDate: '2024-03-31',
variant: 'info',
},
],
},
{
label: 'Frontend Development',
items: [
{
title: 'UI Design',
startDate: '2024-01-15',
endDate: '2024-02-15',
variant: 'warning',
},
{
title: 'Component Dev',
startDate: '2024-02-15',
endDate: '2024-04-15',
variant: 'default',
},
],
},
{
label: 'Testing',
items: [
{
title: 'QA Phase',
startDate: '2024-03-01',
endDate: '2024-04-30',
variant: 'danger',
},
],
},
],
},
},
}
);