-
Notifications
You must be signed in to change notification settings - Fork 4
Expand file tree
/
Copy pathindex.tsx
More file actions
2281 lines (2085 loc) · 87.8 KB
/
Copy pathindex.tsx
File metadata and controls
2281 lines (2085 loc) · 87.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
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/**
* 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 from 'react';
import type { FieldMetadata, SelectOptionMetadata } from '@object-ui/types';
import { ComponentRegistry, percentDisplayValue } from '@object-ui/core';
import { useLocalization } from '@object-ui/i18n';
import { Badge, Avatar, AvatarImage, AvatarFallback, Button, Checkbox, EmptyValue, cn } from '@object-ui/components';
import { Check, X, Copy, Phone as PhoneIcon, MapPin } from 'lucide-react';
import { useObjectTranslation } from '@object-ui/react';
import { SchemaRendererContext as _SchemaRendererContext } from '@object-ui/react';
// Module-level cache so multiple renderers fetching the same lookup ID
// only trigger one network call. Keyed by `${objectName}:${id}`.
type LookupCacheEntry =
| { state: 'pending'; promise: Promise<void> }
| { state: 'ok'; name: string | undefined }
| { state: 'err' };
const lookupNameCache: Map<string, LookupCacheEntry> = new Map();
/**
* Pick the most reasonable display name from an arbitrary record object.
* Tries common name-like keys in priority order, then falls back to undefined.
*/
export function pickRecordDisplayName(
record: Record<string, unknown> | null | undefined,
preferredField?: string,
): string | undefined {
if (!record || typeof record !== 'object') return undefined;
// Caller-provided hint (typically the target object's displayNameField)
// beats every heuristic so domain-specific names like `legal_name` win.
if (preferredField) {
const pv = record[preferredField];
if (typeof pv === 'string' && pv.trim()) return pv.trim();
if (typeof pv === 'number') return String(pv);
}
const candidates = ['name', 'full_name', 'display_name', 'label', 'title', 'subject', 'username'];
for (const k of candidates) {
const v = record[k];
if (typeof v === 'string' && v.trim()) return v.trim();
if (typeof v === 'number') return String(v);
}
// Salesforce-style: build a composite name from common person-record
// fields when no top-level display field is present. Preferred over the
// raw `email` fallback below so `Bob Lin` beats `bob.lin@acme.com`.
const first = record['first_name'];
const last = record['last_name'];
const salutation = record['salutation'];
const composite = [salutation, first, last]
.filter((p) => typeof p === 'string' && (p as string).trim())
.map((p) => (p as string).trim())
.join(' ');
if (composite) return composite;
// Email is the last-resort identifier (better than the opaque id).
const email = record['email'];
if (typeof email === 'string' && email.trim()) return email.trim();
// Heuristic fallback: pick the first string-valued field whose name looks
// like a human-facing identifier (legal_name, framework_name, control_number,
// policy_code, etc.). This covers domain schemas that don't use the
// hardcoded canonical names above. We skip obvious metadata keys.
const SKIP = new Set([
'id', '_id', 'organization_id', 'created_by', 'updated_by',
'created_at', 'updated_at', 'tenant_id',
]);
const SUFFIXES = ['_name', '_title', '_number', '_code', '_label'];
for (const [k, v] of Object.entries(record)) {
if (SKIP.has(k)) continue;
if (k.endsWith('_id')) continue;
if (!SUFFIXES.some((s) => k.endsWith(s))) continue;
if (typeof v === 'string' && v.trim()) return v.trim();
if (typeof v === 'number') return String(v);
}
return undefined;
}
/**
* Heuristic: detect strings that look like opaque foreign-key IDs (e.g. nanoid
* or BSON ObjectId). Used so we don't display random gibberish to users when
* a lookup wasn't expanded.
*/
export function isLikelyOpaqueId(v: unknown): boolean {
if (typeof v !== 'string') return false;
// 12-32 chars, only [A-Za-z0-9_-], no whitespace.
if (!/^[A-Za-z0-9_-]{12,32}$/.test(v)) return false;
// Must have BOTH upper- and lower-case letters (real words rarely do at this length).
// Also accept tokens that contain `_` or `-` separators alongside any case mix.
const hasUpper = /[A-Z]/.test(v);
const hasLower = /[a-z]/.test(v);
const hasDigitOrSep = /[0-9_-]/.test(v);
return (hasUpper && hasLower) || (hasUpper && hasDigitOrSep) || (hasLower && hasDigitOrSep);
}
/**
* Fetch-on-demand resolver for foreign-key IDs that weren't expanded by the
* server. Reads `dataSource` from SchemaRendererContext; safely no-ops if
* the context isn't installed. Returns the resolved display name or
* `undefined` while pending or unresolvable.
*/
function useLookupName(referenceTo: string | undefined, value: unknown, preferredField?: string): string | undefined {
const ctx = React.useContext(_SchemaRendererContext);
const dataSource = ctx?.dataSource;
const [, force] = React.useState(0);
const isResolvable =
!!referenceTo &&
!!dataSource &&
typeof dataSource.find === 'function' &&
(typeof value === 'string' || typeof value === 'number') &&
value !== '';
// The preferred display field is part of the cache identity: two columns
// targeting the same record with different `display_field`s must not
// serve each other's cached name (#2926 ⑧).
const cacheKey = isResolvable ? `${referenceTo}:${String(value)}:${preferredField ?? ''}` : '';
React.useEffect(() => {
if (!isResolvable) return;
const existing = lookupNameCache.get(cacheKey);
if (existing && existing.state !== 'pending' && (existing as any).promise == null) return;
if (existing?.state === 'pending') return;
const promise: Promise<void> = (async () => {
try {
let record: Record<string, unknown> | undefined;
if (typeof (dataSource as any).findOne === 'function') {
record = await (dataSource as any).findOne(referenceTo, value);
} else {
const result = await (dataSource as any).find(referenceTo, {
$filter: { id: value },
options: { $top: 1 },
});
const records: any[] = Array.isArray(result)
? result
: (result?.value || result?.data || []);
record = records[0];
}
const name = pickRecordDisplayName(record, preferredField);
lookupNameCache.set(cacheKey, { state: 'ok', name });
} catch {
lookupNameCache.set(cacheKey, { state: 'err' });
}
force((n) => n + 1);
})();
lookupNameCache.set(cacheKey, { state: 'pending', promise });
}, [cacheKey, isResolvable, referenceTo, value, dataSource]);
if (!isResolvable) return undefined;
const entry = lookupNameCache.get(cacheKey);
return entry?.state === 'ok' ? entry.name : undefined;
}
/**
* Safe label resolver for cell-level UI strings. Falls back to the English
* default when no I18nProvider is available or when the key is missing.
*/
function useFieldLabel() {
try {
const { t } = useObjectTranslation();
return (key: string, fallback: string) => {
const v = t(key);
return !v || v === key ? fallback : v;
};
} catch {
return (_k: string, fallback: string) => fallback;
}
}
import { TextField } from './widgets/TextField';
import { NumberField } from './widgets/NumberField';
import { BooleanField } from './widgets/BooleanField';
import { SelectField } from './widgets/SelectField';
import { DateField } from './widgets/DateField';
import { EmailField } from './widgets/EmailField';
import { PhoneField } from './widgets/PhoneField';
import { UrlField } from './widgets/UrlField';
import { CurrencyField } from './widgets/CurrencyField';
import { TextAreaField } from './widgets/TextAreaField';
import { RichTextField } from './widgets/RichTextField';
import { LookupField } from './widgets/LookupField';
import { CapabilityMultiSelectField } from './widgets/CapabilityMultiSelectField';
import { DateTimeField } from './widgets/DateTimeField';
import { TimeField } from './widgets/TimeField';
import { PercentField } from './widgets/PercentField';
import { PasswordField } from './widgets/PasswordField';
import { FileField } from './widgets/FileField';
import { ImageField } from './widgets/ImageField';
import { LocationField } from './widgets/LocationField';
import { FormulaField } from './widgets/FormulaField';
import { SummaryField } from './widgets/SummaryField';
import { AutoNumberField } from './widgets/AutoNumberField';
import { UserField } from './widgets/UserField';
import { ObjectField } from './widgets/ObjectField';
import { VectorField } from './widgets/VectorField';
import { GridField } from './widgets/GridField';
// New widgets according to @objectstack/spec
import { ColorField } from './widgets/ColorField';
import { SliderField } from './widgets/SliderField';
import { RatingField } from './widgets/RatingField';
import { CodeField } from './widgets/CodeField';
import { AvatarField } from './widgets/AvatarField';
import { AddressField } from './widgets/AddressField';
import { GeolocationField } from './widgets/GeolocationField';
import { SignatureField } from './widgets/SignatureField';
import { QRCodeField } from './widgets/QRCodeField';
import { MasterDetailField } from './widgets/MasterDetailField';
/**
* Cell renderer props
*/
export interface CellRendererProps {
value: any;
field: FieldMetadata;
isEditing?: boolean;
onChange?: (value: any) => void;
}
/**
* Coerce a value to a safe primitive for rendering.
* Handles MongoDB wrapper types ($numberDecimal, $oid, $date), expanded
* reference objects, and arrays so that no raw object is ever passed as
* a React child — preventing React error #310.
*/
export function coerceToSafeValue(value: unknown): string | number | boolean | null | undefined {
if (value == null) return value as null | undefined;
if (typeof value === 'number' || typeof value === 'boolean') return value;
if (typeof value === 'string') {
// A reference/expanded value can arrive as a JSON-encoded object string —
// e.g. an unresolved external-id reference '{"externalId":"Website Relaunch"}'.
// Parse and extract a human label instead of leaking raw JSON into the cell.
const s = value.trim();
if ((s.startsWith('{') && s.endsWith('}')) || (s.startsWith('[') && s.endsWith(']'))) {
try { return coerceToSafeValue(JSON.parse(s)); } catch { /* not JSON — fall through */ }
}
return value;
}
if (value instanceof Date) return value.toISOString();
if (Array.isArray(value)) {
return value.map((v) => {
if (v != null && typeof v === 'object') {
const obj = v as Record<string, unknown>;
return String(obj.name || obj.label || obj.externalId || obj.id || obj._id || '[Object]');
}
return String(v);
}).join(', ');
}
if (typeof value === 'object') {
const obj = value as Record<string, unknown>;
// MongoDB numeric wrapper: { $numberDecimal: "250000" }
if ('$numberDecimal' in obj) return Number(obj.$numberDecimal);
// MongoDB ObjectId wrapper: { $oid: "abc123" }
if ('$oid' in obj) return String(obj.$oid);
// MongoDB date wrapper: { $date: "2024-01-01T00:00:00Z" }
if ('$date' in obj) return String(obj.$date);
// Expanded reference / general object: extract name/label/externalId/id
return String(obj.name || obj.label || obj.externalId || obj.id || obj._id || '[Object]');
}
return String(value);
}
/**
* Format currency value. When `currency` is undefined, falls back to a
* plain number with thousands separators (no symbol). Silently assuming
* USD for unconfigured currency fields was the #1 source of "why is my
* RMB amount showing as dollars?" bug reports.
*
* Trailing `.00` is dropped when the value is a whole number — Salesforce
* convention: `$1,234.50` keeps cents; `$1,234` does not.
*/
import { resolveFieldCurrency } from './currency';
export { resolveFieldCurrency };
export function formatCurrency(value: number, currency?: string): string {
const isWhole = Number.isFinite(value) && value === Math.trunc(value);
const maxFrac = isWhole ? 0 : 2;
if (!currency) {
return formatNumber(value, maxFrac);
}
try {
return new Intl.NumberFormat('en-US', {
style: 'currency',
currency,
minimumFractionDigits: 0,
maximumFractionDigits: maxFrac,
}).format(value);
} catch {
return `${currency} ${value.toFixed(maxFrac)}`;
}
}
/**
* Format currency value in compact form for mobile display.
* E.g., $150,000 → $150K, $1,200,000 → $1.2M
* When `currency` is undefined, returns a compact number without symbol.
*/
export function formatCompactCurrency(value: number, currency?: string): string {
if (!currency) {
try {
const formatted = new Intl.NumberFormat('en-US', {
notation: 'compact',
maximumFractionDigits: 1,
}).format(value);
return formatted.replace(/\.0(?=[KMBT])/, '');
} catch {
return String(value);
}
}
try {
const formatted = new Intl.NumberFormat('en-US', {
style: 'currency',
currency,
notation: 'compact',
maximumFractionDigits: 1,
}).format(value);
// Strip trailing ".0" before compact suffix for consistent cross-environment output
// e.g. "$150.0K" → "$150K" while keeping "$1.5M" intact
return formatted.replace(/\.0(?=[KMBT])/, '');
} catch {
return `${currency} ${value}`;
}
}
/**
* Format a plain number with thousands separators, no currency symbol.
* Used as a safe fallback when a currency-typed field has no `currency`
* configured — we'd rather render `1,234.50` than silently assume USD.
*/
export function formatNumber(value: number, decimals: number = 2): string {
try {
return new Intl.NumberFormat('en-US', {
minimumFractionDigits: decimals,
maximumFractionDigits: decimals,
}).format(value);
} catch {
return value.toFixed(decimals);
}
}
/**
* Format percent value
* Handles both decimal (0.8 = 80%) and whole number (80 = 80%) inputs.
*/
export function formatPercent(value: number, precision: number = 0): string {
// Scale a fraction-stored percent (0.8 → 80%) via the shared core helper, so
// the list cell and the dashboard measure formatter (`formatMeasure`) agree.
const displayValue = percentDisplayValue(value);
return `${displayValue.toFixed(precision)}%`;
}
/**
* Humanize a snake_case or kebab-case string into Title Case.
* Used as fallback label when no explicit option.label exists.
*
* Examples:
* "in_progress" → "In Progress"
* "high-priority" → "High Priority"
* "active" → "Active"
*/
export function humanizeLabel(value: string): string {
return value.replace(/[_-]/g, ' ').replace(/\b\w/g, c => c.toUpperCase());
}
/**
* Format date as relative time (e.g., "2 days ago", "Today", "Overdue 3d")
*
* `dueLike` gates the "Overdue" wording — a past `start_date`/`created_at`
* isn't overdue, only a past due/deadline-semantic field is. Non-due-like
* past dates render as "Nd ago" instead.
*/
export function formatRelativeDate(value: string | Date | number, options?: { dueLike?: boolean }): string {
if (value === null || value === undefined || value === '') return '—';
const date = value instanceof Date ? value : new Date(value as any);
if (!(date instanceof Date) || isNaN(date.getTime())) return '—';
const now = new Date();
const startOfToday = new Date(now.getFullYear(), now.getMonth(), now.getDate());
const startOfDate = new Date(date.getFullYear(), date.getMonth(), date.getDate());
const diffMs = startOfDate.getTime() - startOfToday.getTime();
const diffDays = Math.round(diffMs / (1000 * 60 * 60 * 24));
if (diffDays === 0) return 'Today';
if (diffDays === 1) return 'Tomorrow';
if (diffDays === -1) return 'Yesterday';
if (diffDays < -1) {
const absDays = Math.abs(diffDays);
if (absDays <= 7) return options?.dueLike ? `Overdue ${absDays}d` : `${absDays}d ago`;
return formatDate(date);
}
if (diffDays > 1 && diffDays <= 7) return `In ${diffDays} days`;
return formatDate(date);
}
/**
* Format date value
*/
export function formatDate(value: string | Date | number, style?: string, options?: { dueLike?: boolean }): string {
if (value === null || value === undefined || value === '') return '—';
const date = value instanceof Date ? value : new Date(value as any);
if (!(date instanceof Date) || isNaN(date.getTime())) return '—';
if (style === 'short') {
// Compact format for mobile: "Jan 15, '24"
const month = date.toLocaleDateString('en-US', { month: 'short' });
const day = date.getDate();
const year = String(date.getFullYear()).slice(-2);
return `${month} ${day}, '${year}`;
}
if (style === 'relative') {
return formatRelativeDate(date, options);
}
// Default format: locale-aware human-readable. Drop the year when it
// matches the current year — Salesforce / HubSpot / Linear all do this
// because the year is rarely useful for in-progress records and the
// verbose "2026年7月21日" form crowds cards and table cells. Past- /
// future-year dates keep the year so users can disambiguate.
const isCurrentYear = date.getFullYear() === new Date().getFullYear();
return date.toLocaleDateString(undefined, {
year: isCurrentYear ? undefined : 'numeric',
month: 'short',
day: 'numeric',
});
}
/**
* Format datetime value
*/
export function formatDateTime(value: string | Date | number): string {
if (value === null || value === undefined || value === '') return '—';
const date = value instanceof Date ? value : new Date(value as any);
if (!(date instanceof Date) || isNaN(date.getTime())) return '—';
return date.toLocaleDateString(undefined, {
year: 'numeric',
month: 'short',
day: 'numeric',
hour: '2-digit',
minute: '2-digit',
});
}
/**
* Text field cell renderer
*/
export function TextCellRenderer({ value }: CellRendererProps): React.ReactElement {
const safe = coerceToSafeValue(value);
if (safe == null || safe === '') return <EmptyValue />;
return <span className="truncate">{String(safe)}</span>;
}
/**
* Number field cell renderer
*/
export function NumberCellRenderer({ value, field }: CellRendererProps): React.ReactElement {
if (value == null) return <EmptyValue />;
const safe = coerceToSafeValue(value);
const numField = field as any;
// Decimal places come from `scale` (the `s` in a `decimal(p, s)` column),
// NOT `precision` — `precision` is the TOTAL digit count (`p`), and reading
// it here padded every value out to that width (e.g. `1` from a
// decimal(10, 0) column rendered as "1.0000000000"). When `scale` is
// declared we pad to it so a fixed display is honoured (e.g. an amount with
// scale 2 → "16.00", a field with scale 3 → "3.140"); when it is absent we
// keep the minimum at 0 so trailing zeros are trimmed and only cap the
// maximum (20 = Intl max) to preserve the value's natural precision.
const scale = typeof numField.scale === 'number' ? numField.scale : undefined;
const num = Number(safe);
const formatted = !isNaN(num)
? new Intl.NumberFormat('en-US', {
minimumFractionDigits: scale ?? 0,
maximumFractionDigits: scale ?? 20,
}).format(num)
: String(safe);
return <span className="tabular-nums">{formatted}</span>;
}
/**
* Currency field cell renderer
*/
export function CurrencyCellRenderer({ value, field }: CellRendererProps): React.ReactElement {
if (value == null) return <EmptyValue />;
const safe = coerceToSafeValue(value);
// Resolve the display currency via the shared precedence: field `currency` →
// `currencyConfig.defaultCurrency` → the tenant default (ADR-0053). When none
// is known, render a plain number — never a guessed symbol (silently assuming
// USD mis-displays non-USD orgs, e.g. RMB amounts shown as $).
const { currency: tenantCurrency } = useLocalization();
const currency = resolveFieldCurrency(field as any, tenantCurrency);
const num = Number(safe);
const formatted = !isNaN(num)
? formatCurrency(num, currency)
: String(safe);
return <span className="tabular-nums font-medium whitespace-nowrap">{formatted}</span>;
}
// Fields that store percentage values as whole numbers (0-100) rather than fractions (0-1)
const WHOLE_PERCENT_FIELD_PATTERN = /progress|completion/;
/**
* Percent field cell renderer with mini progress bar
*/
export function PercentCellRenderer({ value, field }: CellRendererProps): React.ReactElement {
if (value == null) return <EmptyValue />;
const safe = coerceToSafeValue(value);
const percentField = field as any;
const precision = percentField.precision ?? 0;
const numValue = Number(safe);
if (isNaN(numValue)) {
return <span className="tabular-nums whitespace-nowrap">{String(safe)}</span>;
}
// Use field name to disambiguate 0-1 fraction vs 0-100 whole number:
// Fields like "progress" or "completion" store values as 0-100, not 0-1
const isWholePercentField = WHOLE_PERCENT_FIELD_PATTERN.test(field?.name?.toLowerCase() || '');
const barValue = isWholePercentField
? numValue
: (numValue > -1 && numValue < 1) ? numValue * 100 : numValue;
const formatted = isWholePercentField ? `${numValue.toFixed(precision)}%` : formatPercent(numValue, precision);
const clampedBar = Math.max(0, Math.min(100, barValue));
return (
<div className="flex items-center gap-2">
<div
className="h-1.5 w-16 rounded-full bg-muted ring-1 ring-inset ring-border/60 overflow-hidden shrink-0"
role="progressbar"
aria-valuenow={clampedBar}
aria-valuemin={0}
aria-valuemax={100}
>
<div
className="h-full rounded-full bg-primary transition-all"
style={{ width: `${clampedBar}%` }}
/>
</div>
<span className="tabular-nums whitespace-nowrap">{formatted}</span>
</div>
);
}
/** Field names that trigger warning badge when boolean value is false */
const STATUS_FIELD_NAMES = new Set([
'active', 'is_active', 'enabled', 'is_enabled', 'verified', 'is_verified',
]);
/**
* Boolean field cell renderer (Airtable-style checkbox)
* Supports semantic rendering for completion fields (green indicator)
* and warning badge for active/enabled fields when false.
*/
export function BooleanCellRenderer({ value, field }: CellRendererProps): React.ReactElement {
if (value == null) {
return <span className="flex items-center justify-center"><EmptyValue /></span>;
}
// Semantic rendering for completion fields (green circle indicator)
// Only match exact field names to avoid false positives
const fieldName = field?.name?.toLowerCase() || '';
const isCompletionField = fieldName === 'completed' || fieldName === 'is_completed'
|| fieldName === 'done' || fieldName === 'is_done';
if (isCompletionField) {
return (
<div className="flex items-center justify-center">
{value ? (
<div className="size-5 rounded-full bg-green-500 flex items-center justify-center" role="img" aria-label="Completed" data-testid="completion-indicator">
<Check className="size-3 text-white" />
</div>
) : (
<div className="size-5 rounded-full border-2 border-muted-foreground/30" role="img" aria-label="Not completed" data-testid="completion-indicator" />
)}
</div>
);
}
// Warning badge for active/enabled fields when false
if (STATUS_FIELD_NAMES.has(fieldName) && !value) {
return (
<Badge variant="destructive" className="text-xs" data-testid="boolean-warning-badge">
{field?.label || humanizeLabel(fieldName)} — Off
</Badge>
);
}
return (
<div className="flex items-center justify-start">
<Checkbox checked={!!value} disabled className="pointer-events-none" />
</div>
);
}
/**
* Date field cell renderer
*/
export function DateCellRenderer({ value, field }: CellRendererProps): React.ReactElement {
if (!value) return <EmptyValue />;
const safe = coerceToSafeValue(value);
const dateField = field as any;
const style = dateField.format || 'relative';
// A date is only *semantically* a due/deadline when the field says so — a
// plain "start_date" or "created_at" in the past is neither overdue text
// nor red, even though it renders in the same relative-time style.
const fieldName = String(dateField?.name || dateField?.accessorKey || dateField?.key || '').toLowerCase();
const dueLike =
dateField?.dueLike === true ||
/(^|_)(due|deadline|expires?|expiry|expiration|expected_close|target_close|sla|return_by|renewal|next_action)(_|$)/.test(fieldName);
const formatted = formatDate(safe as string | Date, style, { dueLike });
const date = safe != null ? new Date(safe as string | number) : null;
const isValidDate = date !== null && !isNaN(date.getTime());
const startOfToday = new Date();
startOfToday.setHours(0, 0, 0, 0);
const isOverdue = dueLike && isValidDate && date! < startOfToday;
const isoString = isValidDate ? date!.toISOString() : String(safe);
return (
<span
className={`tabular-nums${isOverdue ? ' text-red-600' : ''}`}
title={isoString}
>
{formatted}
</span>
);
}
/**
* DateTime field cell renderer (Airtable-style with date and time visually separated)
*/
export function DateTimeCellRenderer({ value }: CellRendererProps): React.ReactElement {
if (!value) return <EmptyValue />;
const safe = coerceToSafeValue(value);
const date = safe != null ? new Date(safe as string | number) : null;
if (date === null || isNaN(date.getTime())) return <EmptyValue />;
const datePart = date.toLocaleDateString(undefined, {
month: 'numeric',
day: 'numeric',
year: 'numeric',
});
const timePart = date.toLocaleTimeString(undefined, {
hour: 'numeric',
minute: '2-digit',
hour12: true,
}).toLowerCase();
return (
<span className="tabular-nums text-sm whitespace-nowrap">
<span>{datePart}</span>
<span className="ml-2 text-muted-foreground">{timePart}</span>
</span>
);
}
// Semantic color mapping (auto-detect from value text for priority & status fields)
// Keys use underscore notation; lookup normalizes spaces/hyphens to underscores automatically.
// Chinese keys are stored as-is and matched directly (no normalization side-effects).
const SEMANTIC_COLOR_MAP: Record<string, string> = {
// Priority values (en)
critical: 'red',
urgent: 'red',
high: 'orange',
medium: 'yellow',
normal: 'blue',
low: 'gray',
none: 'gray',
// Status values (en)
paid: 'green',
completed: 'green',
done: 'green',
active: 'green',
approved: 'green',
resolved: 'green',
pending: 'yellow',
waiting: 'yellow',
on_hold: 'yellow',
shipped: 'blue',
in_progress: 'blue',
open: 'blue',
processing: 'blue',
draft: 'gray',
new: 'gray',
inactive: 'gray',
closed: 'gray',
cancelled: 'red',
canceled: 'red',
rejected: 'red',
failed: 'red',
overdue: 'red',
delivered: 'purple',
archived: 'indigo',
// CRM lifecycle values (en)
contacted: 'blue',
qualified: 'purple',
converted: 'green',
won: 'green',
lost: 'red',
// Priority values (zh)
紧急: 'red',
严重: 'red',
高: 'orange',
中: 'yellow',
普通: 'blue',
低: 'gray',
无: 'gray',
// Status values (zh)
新建: 'gray',
草稿: 'gray',
待处理: 'yellow',
待审核: 'yellow',
待联系: 'yellow',
挂起: 'yellow',
进行中: 'blue',
处理中: 'blue',
已联系: 'blue',
跟进中: 'blue',
已发货: 'blue',
打开: 'blue',
已确认: 'green',
已审核: 'green',
已通过: 'green',
已完成: 'green',
已支付: 'green',
已签收: 'green',
已转化: 'green',
成单: 'green',
赢得: 'green',
已签约: 'green',
已交付: 'purple',
已归档: 'indigo',
已关闭: 'gray',
已取消: 'red',
已拒绝: 'red',
失败: 'red',
逾期: 'red',
流失: 'red',
丢失: 'red',
};
// Color to Tailwind class mapping for custom Badge styling
// Color → Tailwind class mapping for status-style badges.
// Uses the modern "soft pill" pattern (Tailwind UI style): -50 background,
// -700 text, hairline -200 border. Dark mode mirrors with -950/40 surface
// and -300 text. This keeps status fields readable without the heavy,
// candy-colored look of the older -100/-300/-800 combination.
const BADGE_COLOR_MAP: Record<string, string> = {
gray: 'bg-gray-50 text-gray-700 border-gray-200 dark:bg-gray-800/50 dark:text-gray-200 dark:border-gray-700/60',
red: 'bg-red-50 text-red-700 border-red-200 dark:bg-red-950/40 dark:text-red-300 dark:border-red-900/60',
orange: 'bg-orange-50 text-orange-700 border-orange-200 dark:bg-orange-950/40 dark:text-orange-300 dark:border-orange-900/60',
yellow: 'bg-yellow-50 text-yellow-800 border-yellow-200 dark:bg-yellow-950/40 dark:text-yellow-300 dark:border-yellow-900/60',
green: 'bg-green-50 text-green-700 border-green-200 dark:bg-green-950/40 dark:text-green-300 dark:border-green-900/60',
blue: 'bg-blue-50 text-blue-700 border-blue-200 dark:bg-blue-950/40 dark:text-blue-300 dark:border-blue-900/60',
indigo: 'bg-indigo-50 text-indigo-700 border-indigo-200 dark:bg-indigo-950/40 dark:text-indigo-300 dark:border-indigo-900/60',
purple: 'bg-purple-50 text-purple-700 border-purple-200 dark:bg-purple-950/40 dark:text-purple-300 dark:border-purple-900/60',
pink: 'bg-pink-50 text-pink-700 border-pink-200 dark:bg-pink-950/40 dark:text-pink-300 dark:border-pink-900/60',
};
// Solid color → Tailwind background class for the small dot used by the
// `appearance: 'dot'` rendering of select/status fields. Uses the -500 shade
// for both light and dark modes so the dot remains a clear visual anchor
// without becoming a heavy color block.
const DOT_COLOR_MAP: Record<string, string> = {
gray: 'bg-gray-400 dark:bg-gray-500',
red: 'bg-red-500',
orange: 'bg-orange-500',
yellow: 'bg-yellow-500',
green: 'bg-green-500',
blue: 'bg-blue-500',
indigo: 'bg-indigo-500',
purple: 'bg-purple-500',
pink: 'bg-pink-500',
};
// Color palette used by the deterministic fallback when no schema/semantic
// color matches. Excludes 'gray' to ensure visual contrast between values.
const BADGE_FALLBACK_PALETTE: readonly string[] = [
'blue', 'green', 'purple', 'orange', 'pink', 'indigo', 'yellow', 'red',
];
/**
* Stable string hash (djb2-ish) → palette index.
* Same value always yields the same color across renders/sessions.
*/
function hashToColor(value: string): string {
let h = 5381;
for (let i = 0; i < value.length; i++) {
h = ((h << 5) + h) ^ value.charCodeAt(i);
}
const idx = Math.abs(h) % BADGE_FALLBACK_PALETTE.length;
return BADGE_FALLBACK_PALETTE[idx];
}
/**
* Map a hex color (e.g. '#8B5CF6') to the nearest named palette color the
* badge/dot maps understand. Object field options almost always declare colors
* as HEX, so without this the explicit author color is ignored and a semantic/
* hash heuristic takes over (e.g. a purple 'In Review' rendered alarming-red).
* Low-saturation hexes resolve to 'gray'; otherwise bucket by hue.
*/
function hexToPaletteName(hex: string): string | undefined {
const m = /^#?([0-9a-fA-F]{3}|[0-9a-fA-F]{6})$/.exec(hex.trim());
if (!m) return undefined;
let h = m[1];
if (h.length === 3) h = h.split('').map((c) => c + c).join('');
const r = parseInt(h.slice(0, 2), 16) / 255;
const g = parseInt(h.slice(2, 4), 16) / 255;
const b = parseInt(h.slice(4, 6), 16) / 255;
const max = Math.max(r, g, b), min = Math.min(r, g, b), d = max - min;
const l = (max + min) / 2;
const sat = d === 0 ? 0 : d / (1 - Math.abs(2 * l - 1));
if (sat < 0.22) return 'gray';
let hue: number;
if (max === r) hue = (((g - b) / d) % 6 + 6) % 6;
else if (max === g) hue = (b - r) / d + 2;
else hue = (r - g) / d + 4;
hue *= 60;
if (hue >= 345 || hue < 15) return 'red';
if (hue < 30) return 'orange';
if (hue < 60) return 'yellow';
if (hue < 170) return 'green';
if (hue < 238) return 'blue';
if (hue < 250) return 'indigo';
if (hue < 295) return 'purple';
return 'pink';
}
/** Normalize an option color to a named palette key: pass known names through,
* resolve hex to the nearest palette color, else undefined. */
function resolveColorName(color?: string): string | undefined {
if (!color) return undefined;
if (BADGE_COLOR_MAP[color]) return color;
if (color.charAt(0) === '#') return hexToPaletteName(color);
return undefined;
}
export function getBadgeColorClasses(color?: string, val?: unknown): string {
const named = resolveColorName(color);
if (named && BADGE_COLOR_MAP[named]) return BADGE_COLOR_MAP[named];
if (val == null || val === '') return 'bg-muted text-muted-foreground border-border';
const key = String(val).toLowerCase().replace(/[\s-]/g, '_');
const semantic = SEMANTIC_COLOR_MAP[key];
if (semantic && BADGE_COLOR_MAP[semantic]) return BADGE_COLOR_MAP[semantic];
// Deterministic fallback so distinct values are visually distinguishable
// even when metadata declares no colors.
return BADGE_COLOR_MAP[hashToColor(key)];
}
/**
* Resolve a semantic color name (e.g. "red", "green") for a value, suitable
* for callers that need a raw color token rather than CSS classes (for
* example, the Gantt renderer paints bars via inline styles).
*
* Resolution order: explicit option color → semantic value mapping →
* deterministic hash fallback. Returns `undefined` only when no value is
* supplied so the caller can fall back to its own default.
*/
export function getSemanticColorName(color?: string, val?: unknown): string | undefined {
const named = resolveColorName(color);
if (named && BADGE_COLOR_MAP[named]) return named;
if (val == null || val === '') return undefined;
const key = String(val).toLowerCase().replace(/[\s-]/g, '_');
const semantic = SEMANTIC_COLOR_MAP[key];
if (semantic) return semantic;
return hashToColor(key);
}
// Resolved hex values for the -500 shade of each palette color. Mirrors
// `DOT_COLOR_MAP` and is consumed by callers that paint via inline styles
// (e.g. Gantt task bars, where Tailwind classes can't be applied to dynamic
// `style={}` values).
const COLOR_NAME_HEX: Record<string, string> = {
gray: '#6b7280',
red: '#ef4444',
orange: '#f97316',
yellow: '#eab308',
green: '#22c55e',
blue: '#3b82f6',
indigo: '#6366f1',
purple: '#a855f7',
pink: '#ec4899',
};
/**
* Map a semantic color name to its Tailwind -500 hex value. Used by
* inline-style consumers (Gantt bars). Falls back to the supplied default
* (or the platform default blue) when the name is unrecognized.
*/
export function getSemanticHex(name?: string, fallback: string = '#3b82f6'): string {
if (!name) return fallback;
return COLOR_NAME_HEX[name] ?? fallback;
}
/**
* Select field cell renderer.
*
* Two visual styles, controlled by `field.appearance` (renderer-level option,
* not part of the `@objectstack/spec` field schema):
* - `'badge'` (default for spec compatibility): soft-pill colored badge.
* - `'dot'`: a small colored dot followed by the option label. Used by
* dense list/grid contexts to keep the table visually quiet — repeated
* filled badges across many rows create heavy visual noise.
*
* Metadata always wins: callers can pass `appearance: 'badge'` on the field
* descriptor to force the legacy badge in any context.
*/
export function SelectCellRenderer({ value, field }: CellRendererProps): React.ReactElement {
const selectField = field as any;
const options: SelectOptionMetadata[] = selectField.options || [];
const appearance: 'badge' | 'dot' = selectField.appearance === 'dot' ? 'dot' : 'badge';
if (value == null || value === '') return <EmptyValue />;
// Match a stored value to a configured option, falling back to a
// case-insensitive comparison so seed data with mixed case
// (e.g. "Referral" stored, "referral" defined) still resolves to the
// localized option label.
const findOption = (val: any): SelectOptionMetadata | undefined => {
const exact = options.find(opt => opt.value === val);
if (exact) return exact;
const norm = String(val).toLowerCase();
return options.find(opt => String(opt.value).toLowerCase() === norm);
};
const renderOne = (val: any, key?: number): React.ReactElement => {
const option = findOption(val);
const label = option?.label || humanizeLabel(String(val));
if (appearance === 'dot') {
// Resolve a real CSS color for the dot. Prefer explicit option color,
// then semantic mapping for the value, then deterministic palette.
const colorName = resolveColorName(option?.color)
|| SEMANTIC_COLOR_MAP[String(val).toLowerCase().replace(/[\s-]/g, '_')]
|| hashToColor(String(val).toLowerCase().replace(/[\s-]/g, '_'));
const dotClass = DOT_COLOR_MAP[colorName] || DOT_COLOR_MAP.gray;
return (
<span key={key} className="inline-flex items-center gap-1.5 text-sm">
<span className={cn('h-1.5 w-1.5 rounded-full shrink-0', dotClass)} aria-hidden="true" />
<span className="truncate">{label}</span>
</span>
);
}
const colorClasses = getBadgeColorClasses(option?.color, val);
return (
<Badge
key={key}
variant="outline"
className={colorClasses}
>
{label}
</Badge>
);
};
// Handle multiple values
if (Array.isArray(value)) {
return (
<div className={cn('flex flex-wrap', appearance === 'dot' ? 'gap-x-3 gap-y-1' : 'gap-1')}>
{value.map((val, idx) => renderOne(val, idx))}
</div>
);
}
return renderOne(value);
}
/**
* Email field cell renderer
*/
export function EmailCellRenderer({ value }: CellRendererProps): React.ReactElement {
if (!value) return <EmptyValue />;
const label = useFieldLabel();
const safe = String(coerceToSafeValue(value) ?? '');
const [copied, setCopied] = React.useState(false);
const handleCopy = (e: React.MouseEvent) => {
e.stopPropagation();
e.preventDefault();
navigator.clipboard.writeText(safe).then(() => {
setCopied(true);
setTimeout(() => setCopied(false), 2000);
}).catch(() => { /* clipboard not available */ });
};
return (
<span className="inline-flex items-center gap-1 group/email">
<Button
variant="link"
className="p-0 h-auto font-normal text-blue-600 hover:text-blue-800"
asChild
>