-
Notifications
You must be signed in to change notification settings - Fork 5
Expand file tree
/
Copy pathViewTabBar.tsx
More file actions
898 lines (858 loc) · 34.3 KB
/
Copy pathViewTabBar.tsx
File metadata and controls
898 lines (858 loc) · 34.3 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
/**
* 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.
*/
/**
* ViewTabBar Component
*
* A reusable view tab bar with:
* - Inline "+" Add View button
* - Right-click context menu (rename, duplicate, delete, set as default, share)
* - Overflow → "More" dropdown when maxVisibleTabs exceeded
* - Filter/sort indicator badges on tabs
* - "Save as View" button when user filters differ from saved state
* - Double-click to rename view tab inline
* - Drag-reorder view tabs (Phase 2)
* - Pin/favorite views (Phase 2)
* - View type quick-switch palette (Phase 2)
* - Personal vs. shared views grouping (Phase 2)
*/
import React, { useState, useRef, useEffect, useCallback, useMemo, type ComponentType } from 'react';
import {
cn,
ContextMenu,
ContextMenuTrigger,
ContextMenuContent,
ContextMenuItem,
ContextMenuSeparator,
ContextMenuSub,
ContextMenuSubTrigger,
ContextMenuSubContent,
DropdownMenu,
DropdownMenuTrigger,
DropdownMenuContent,
DropdownMenuItem,
DropdownMenuSeparator,
DropdownMenuSub,
DropdownMenuSubTrigger,
DropdownMenuSubContent,
Input,
Button,
Tooltip,
TooltipTrigger,
TooltipContent,
TooltipProvider,
} from '@object-ui/components';
import {
Plus,
MoreHorizontal,
Pencil,
Copy,
Trash2,
Star,
Share2,
Save,
Table as TableIcon,
Pin,
PinOff,
Lock,
Globe,
GripVertical,
LayoutGrid,
Settings2,
ChevronDown,
ListOrdered,
Filter as FilterIcon,
ArrowUpDown,
} from 'lucide-react';
import {
DndContext,
closestCenter,
KeyboardSensor,
PointerSensor,
useSensor,
useSensors,
type DragEndEvent,
type DraggableSyntheticListeners,
} from '@dnd-kit/core';
import {
SortableContext,
horizontalListSortingStrategy,
useSortable,
arrayMove,
} from '@dnd-kit/sortable';
import { CSS } from '@dnd-kit/utilities';
import type { ViewTabBarConfig } from '@object-ui/types';
import { useObjectTranslation } from '@object-ui/react';
function useViewTabLabel() {
// useObjectTranslation is provider-safe (never throws); no try/catch, which
// would wrap the hook call and violate rules-of-hooks. The `fallback` still
// applies below when the key is missing/untranslated.
const { t } = useObjectTranslation();
return (key: string, fallback: string, vars?: Record<string, unknown>): string => {
const v = t(key, vars as any);
// i18next's `t()` is typed `string | object`; coerce so render sites and
// aria-labels always receive a string (an object child white-screens React).
return !v || v === key ? fallback : String(v);
};
}
/** Visibility group sort order: private → team → organization → public */
const VISIBILITY_ORDER: Record<string, number> = { private: 0, team: 1, organization: 2, public: 3 };
/** Minimum drag distance in pixels to activate reorder (large enough to avoid blocking clicks) */
const DRAG_ACTIVATION_DISTANCE = 8;
/** A single view definition for the tab bar */
export interface ViewTabItem {
/** Unique view identifier */
id: string;
/** Display label */
label: string;
/** View type (grid, kanban, calendar, etc.) */
type: string;
/** Whether this view has active filters */
hasActiveFilters?: boolean;
/** Whether this view has active sort */
hasActiveSort?: boolean;
/** Whether this is the default view */
isDefault?: boolean;
/** Whether this view is pinned/favorited */
isPinned?: boolean;
/** View visibility for grouping */
visibility?: 'private' | 'team' | 'organization' | 'public';
/**
* Whether this view is *read-only* (e.g. a System View loaded from
* code/metadata, or a view the current user lacks permission to mutate).
*
* When `true`, mutation menu items (Edit configuration, Rename, Set as
* default, Pin, Change view type, Delete) are hidden from the tab's
* dropdown / context menu, the inline-rename trigger is disabled, and a
* lock icon is rendered next to the label. *Duplicate* remains available
* because it produces a fresh override and does not mutate the source.
*/
readonly?: boolean;
/** Optional tooltip shown alongside the lock icon when `readonly` is true. */
readonlyReason?: string;
}
/** Available view type for quick-switch palette */
export interface AvailableViewType {
type: string;
label: string;
description?: string;
}
export interface ViewTabBarProps {
/** Views to render as tabs */
views: ViewTabItem[];
/** Currently active view ID */
activeViewId: string;
/** Callback when a view tab is clicked */
onViewChange: (viewId: string) => void;
/** Icon map: view type → React component */
viewTypeIcons?: Record<string, ComponentType<{ className?: string }>>;
/** Configuration for the tab bar UX */
config?: ViewTabBarConfig;
// --- Action callbacks ---
/** Called when "+" button is clicked to add a new view */
onAddView?: () => void;
/** Called when a view is renamed via context menu or double-click */
onRenameView?: (viewId: string, newName: string) => void;
/**
* Called when a view is duplicated. **Opt-in**: the Duplicate menu item
* renders only when a host wires this. It is a deliberate generic affordance
* of this reusable tab bar (duplicate = a fresh override, even for read-only
* views) — not dead code. The console currently does not wire it (runtime
* view duplication is deferred to the per-user personalisation work,
* objectui#1520); omit the prop to hide the affordance.
*/
onDuplicateView?: (viewId: string) => void;
/** Called when a view is deleted */
onDeleteView?: (viewId: string) => void;
/** Called when a view is set as default */
onSetDefaultView?: (viewId: string) => void;
/** Called when a view is shared */
onShareView?: (viewId: string) => void;
/** Called when "Save as View" is clicked */
onSaveAsView?: () => void;
/** Called when a view is pinned/unpinned */
onPinView?: (viewId: string, pinned: boolean) => void;
/** Called when views are reordered via drag */
onReorderViews?: (viewIds: string[]) => void;
/** Called when a view type is changed via quick-switch */
onChangeViewType?: (viewId: string, newType: string) => void;
/** Called when user clicks the gear icon to configure a view */
onConfigView?: (viewId: string) => void;
/** Called when user opens the "Manage views" dialog */
onManageViews?: () => void;
/** Available view types for quick-switch palette */
availableViewTypes?: AvailableViewType[];
/** Whether user has unsaved filter/sort changes (shows "Save as View" indicator) */
hasUnsavedChanges?: boolean;
/** Called when user clicks "Reset" to discard changes */
onResetChanges?: () => void;
/** Additional CSS class */
className?: string;
}
// --- Sortable Tab wrapper ---
const SortableTab: React.FC<{
id: string;
disabled?: boolean;
children: (props: {
setNodeRef: (node: HTMLElement | null) => void;
style: React.CSSProperties;
listeners: DraggableSyntheticListeners;
attributes: Record<string, unknown>;
isDragging: boolean;
}) => React.ReactNode;
}> = ({ id, disabled, children }) => {
const {
attributes,
listeners,
setNodeRef,
transform,
transition,
isDragging,
} = useSortable({ id, disabled, attributes: { role: 'tab', roleDescription: 'view tab', tabIndex: 0 } });
const style: React.CSSProperties = {
transform: CSS.Transform.toString(transform),
transition,
zIndex: isDragging ? 10 : undefined,
opacity: isDragging ? 0.5 : undefined,
};
return <>{children({ setNodeRef, style, listeners, attributes: attributes as unknown as Record<string, unknown>, isDragging })}</>;
};
/**
* ViewTabBar — Airtable/Salesforce-style view tab bar with management UX.
*/
export const ViewTabBar: React.FC<ViewTabBarProps> = ({
views,
activeViewId,
onViewChange,
viewTypeIcons = {},
config = {},
onAddView,
onRenameView,
onDuplicateView,
onDeleteView,
onSetDefaultView,
onShareView,
onSaveAsView,
onPinView,
onReorderViews,
onChangeViewType,
onConfigView,
onManageViews,
availableViewTypes,
hasUnsavedChanges = false,
onResetChanges,
className,
}) => {
const {
showAddButton = true,
inlineRename = true,
contextMenu: enableContextMenu = true,
reorderable = false,
maxVisibleTabs = 4,
showIndicators = true,
showSaveAsView = true,
showPinnedSection = true,
showVisibilityGroups = false,
} = config;
const viewTabLabel = useViewTabLabel();
// --- Inline rename state ---
const [renamingViewId, setRenamingViewId] = useState<string | null>(null);
const [renameValue, setRenameValue] = useState('');
const renameInputRef = useRef<HTMLInputElement>(null);
useEffect(() => {
if (renamingViewId && renameInputRef.current) {
renameInputRef.current.focus();
renameInputRef.current.select();
}
}, [renamingViewId]);
const startRename = useCallback((viewId: string) => {
if (!inlineRename || !onRenameView) return;
const view = views.find(v => v.id === viewId);
if (!view) return;
if (view.readonly) return; // System views cannot be renamed.
setRenamingViewId(viewId);
setRenameValue(view.label);
}, [inlineRename, onRenameView, views]);
const commitRename = useCallback(() => {
if (renamingViewId && renameValue.trim() && onRenameView) {
onRenameView(renamingViewId, renameValue.trim());
}
setRenamingViewId(null);
setRenameValue('');
}, [renamingViewId, renameValue, onRenameView]);
const cancelRename = useCallback(() => {
setRenamingViewId(null);
setRenameValue('');
}, []);
/**
* Suppress the per-tab readonly lock indicator when *every* view is
* readonly — in that case the badge is pure noise (no actionable contrast
* with editable views) and clutters the tab bar. The lock still appears
* the moment the user creates a saved/editable view alongside the system
* ones, so the affordance returns when it actually distinguishes things.
*/
const allReadonly = useMemo(
() => views.length > 0 && views.every(v => !!v.readonly),
[views],
);
// --- Sort views: pinned first → personal → shared ---
const sortedViews = useMemo(() => {
const sorted = [...views];
sorted.sort((a, b) => {
// Pinned views first
if (showPinnedSection) {
const aPinned = a.isPinned ? 1 : 0;
const bPinned = b.isPinned ? 1 : 0;
if (aPinned !== bPinned) return bPinned - aPinned;
}
// Visibility grouping: private → team → organization → public
if (showVisibilityGroups) {
const aOrder = VISIBILITY_ORDER[a.visibility || 'public'] ?? VISIBILITY_ORDER['public'];
const bOrder = VISIBILITY_ORDER[b.visibility || 'public'] ?? VISIBILITY_ORDER['public'];
if (aOrder !== bOrder) return aOrder - bOrder;
}
return 0;
});
return sorted;
}, [views, showPinnedSection, showVisibilityGroups]);
// --- Overflow ---
// Ensure the active view is always visible (Airtable parity) — promote it
// from overflow into the visible set so users never lose track of where
// they are after creating/duplicating a view.
const { visibleViews, overflowViews } = useMemo(() => {
const head = sortedViews.slice(0, maxVisibleTabs);
const tail = sortedViews.slice(maxVisibleTabs);
const activeInTail = tail.findIndex(v => v.id === activeViewId);
if (activeInTail === -1) return { visibleViews: head, overflowViews: tail };
const promoted = tail[activeInTail];
const newHead = head.length > 0 ? [...head.slice(0, -1), promoted] : [promoted];
const demoted = head.length > 0 ? head[head.length - 1] : null;
const newTail = tail.filter((_, i) => i !== activeInTail);
if (demoted) newTail.unshift(demoted);
return { visibleViews: newHead, overflowViews: newTail };
}, [sortedViews, maxVisibleTabs, activeViewId]);
// --- Drag-reorder sensors ---
const sensors = useSensors(
useSensor(PointerSensor, { activationConstraint: { distance: DRAG_ACTIVATION_DISTANCE } }),
useSensor(KeyboardSensor),
);
const handleDragEnd = useCallback((event: DragEndEvent) => {
const { active, over } = event;
if (!over || active.id === over.id || !onReorderViews) return;
const oldIndex = sortedViews.findIndex(v => v.id === active.id);
const newIndex = sortedViews.findIndex(v => v.id === over.id);
if (oldIndex === -1 || newIndex === -1) return;
const reordered = arrayMove(sortedViews, oldIndex, newIndex);
onReorderViews(reordered.map(v => v.id));
}, [sortedViews, onReorderViews]);
const DefaultIcon = TableIcon;
// Determine if a visibility separator should appear before this view
const shouldShowVisibilitySeparator = useCallback((index: number) => {
if (!showVisibilityGroups || index === 0) return false;
const prev = visibleViews[index - 1];
const curr = visibleViews[index];
const isPrivate = (v: ViewTabItem) => v.visibility === 'private';
return isPrivate(prev) && !isPrivate(curr);
}, [showVisibilityGroups, visibleViews]);
// --- Render a single tab ---
const renderTab = (view: ViewTabItem, index: number) => {
const isActive = view.id === activeViewId;
const ViewIcon = viewTypeIcons[view.type] || DefaultIcon;
const isRenaming = renamingViewId === view.id;
const hasIndicator = showIndicators && (view.hasActiveFilters || view.hasActiveSort);
const showSeparator = shouldShowVisibilitySeparator(index);
/**
* System / read-only views suppress mutation menu items so the UI does
* not advertise actions that would no-op (or worse, surprise the user
* by silently failing in the host's onRename/onDelete handlers).
*/
const isReadonly = !!view.readonly;
const getVisibilityIcon = (view: ViewTabItem) => {
if (!showVisibilityGroups) return null;
if (view.visibility === 'private') {
return <Lock data-testid={`view-tab-visibility-${view.id}`} className="h-3 w-3 text-muted-foreground shrink-0" />;
}
if (view.visibility) {
return <Globe data-testid={`view-tab-visibility-${view.id}`} className="h-3 w-3 text-muted-foreground shrink-0" />;
}
return null;
};
const visibilityIcon = getVisibilityIcon(view);
const buildTabContent = (dragHandleProps?: {
listeners: DraggableSyntheticListeners;
attributes: Record<string, unknown>;
isDragging?: boolean;
}) => (
<div
data-testid={`view-tab-${view.id}`}
role="tab"
tabIndex={0}
aria-selected={isActive}
onClick={() => !isRenaming && onViewChange(view.id)}
onDoubleClick={() => startRename(view.id)}
onKeyDown={(e: React.KeyboardEvent<HTMLDivElement>) => {
if (!isRenaming && (e.key === 'Enter' || e.key === ' ')) {
e.preventDefault();
onViewChange(view.id);
}
}}
{...(dragHandleProps?.listeners ?? {})}
{...(dragHandleProps?.attributes ?? {})}
className={cn(
'group/tab inline-flex items-center gap-1.5 px-3 py-2 text-sm font-medium border-b-2 transition-colors whitespace-nowrap relative outline-none focus-visible:ring-2 focus-visible:ring-ring',
dragHandleProps?.isDragging ? 'cursor-grabbing' : 'cursor-pointer',
isActive
? 'border-primary text-primary'
: 'border-transparent text-muted-foreground hover:text-foreground hover:border-border'
)}
>
{reorderable && onReorderViews && (
<span
data-testid={`view-tab-drag-handle-${view.id}`}
aria-hidden="true"
className={cn(
'text-muted-foreground transition-opacity pointer-events-none',
'opacity-0 group-hover/tab:opacity-100',
dragHandleProps?.isDragging && 'opacity-100'
)}
>
<GripVertical className="h-3 w-3" />
</span>
)}
{showPinnedSection && view.isPinned && (
<Pin data-testid={`view-tab-pin-indicator-${view.id}`} className="h-3 w-3 text-primary shrink-0" />
)}
{visibilityIcon}
<ViewIcon className="h-3.5 w-3.5" />
{isRenaming ? (
<Input
ref={renameInputRef}
data-testid={`view-tab-rename-input-${view.id}`}
value={renameValue}
onChange={(e: React.ChangeEvent<HTMLInputElement>) => setRenameValue(e.target.value)}
onBlur={commitRename}
onKeyDown={(e: React.KeyboardEvent<HTMLInputElement>) => {
if (e.key === 'Enter') commitRename();
if (e.key === 'Escape') cancelRename();
}}
className="h-5 w-24 px-1 py-0 text-sm border-none focus-visible:ring-1"
onClick={(e: React.MouseEvent<HTMLInputElement>) => e.stopPropagation()}
/>
) : (
<span>{view.label}</span>
)}
{isReadonly && !allReadonly && (
<Tooltip>
<TooltipTrigger asChild>
<Lock
data-testid={`view-tab-readonly-${view.id}`}
aria-label={viewTabLabel('view.readonlyAriaLabel', 'Read-only view')}
className="h-3 w-3 text-muted-foreground shrink-0"
/>
</TooltipTrigger>
<TooltipContent side="bottom" className="text-xs">
{view.readonlyReason || viewTabLabel('view.readonlyTooltip', 'System view — defined in code, read-only.')}
</TooltipContent>
</Tooltip>
)}
{hasIndicator && (
<Tooltip>
<TooltipTrigger asChild>
<span
data-testid={`view-tab-indicator-${view.id}`}
className="ml-1 inline-flex items-center gap-0.5 h-4 px-1 rounded-full bg-primary/10 text-primary shrink-0"
>
{view.hasActiveFilters && <FilterIcon className="h-2.5 w-2.5" />}
{view.hasActiveSort && <ArrowUpDown className="h-2.5 w-2.5" />}
</span>
</TooltipTrigger>
<TooltipContent side="bottom" className="text-xs">
{[view.hasActiveFilters && 'Active filters', view.hasActiveSort && 'Active sort'].filter(Boolean).join(', ')}
</TooltipContent>
</Tooltip>
)}
{view.isDefault && (
<Star className="h-3 w-3 text-amber-500 fill-amber-500 shrink-0" />
)}
{isActive && (onConfigView || onRenameView || onDuplicateView || onDeleteView) && (
<DropdownMenu>
<DropdownMenuTrigger asChild>
<button
type="button"
data-testid={`view-tab-actions-${view.id}`}
className="ml-0.5 h-4 w-4 flex items-center justify-center rounded hover:bg-accent shrink-0 opacity-70 hover:opacity-100 transition-opacity"
onClick={(e) => e.stopPropagation()}
onPointerDown={(e) => e.stopPropagation()}
onMouseDown={(e) => e.stopPropagation()}
aria-label={viewTabLabel('view.tabActionsFor', `View actions for ${view.label}`, { name: view.label })}
>
<ChevronDown className="h-3 w-3" />
</button>
</DropdownMenuTrigger>
<DropdownMenuContent
align="start"
className="min-w-[180px]"
onClick={(e) => e.stopPropagation()}
>
{onConfigView && !isReadonly && (
<DropdownMenuItem
data-testid={`view-tab-menu-config-${view.id}`}
onClick={() => onConfigView(view.id)}
>
<Settings2 className="h-4 w-4 mr-2" /> {viewTabLabel('view.editViewConfig', 'Edit view config')}
</DropdownMenuItem>
)}
{onRenameView && !isReadonly && (
<DropdownMenuItem
data-testid={`view-tab-menu-rename-${view.id}`}
onClick={() => startRename(view.id)}
>
<Pencil className="h-4 w-4 mr-2" /> {viewTabLabel('view.rename', 'Rename')}
</DropdownMenuItem>
)}
{onDuplicateView && (
<DropdownMenuItem
data-testid={`view-tab-menu-duplicate-${view.id}`}
onClick={() => onDuplicateView(view.id)}
>
<Copy className="h-4 w-4 mr-2" /> {viewTabLabel('view.duplicateView', 'Duplicate view')}
</DropdownMenuItem>
)}
{onShareView && (
<DropdownMenuItem
data-testid={`view-tab-menu-share-${view.id}`}
onClick={() => onShareView(view.id)}
>
<Share2 className="h-4 w-4 mr-2" /> {viewTabLabel('view.shareView', 'Share view')}
</DropdownMenuItem>
)}
{onSetDefaultView && !isReadonly && (
<DropdownMenuItem
data-testid={`view-tab-menu-default-${view.id}`}
onClick={() => onSetDefaultView(view.id)}
>
<Star className="h-4 w-4 mr-2" /> {viewTabLabel('view.setAsDefault', 'Set as default')}
</DropdownMenuItem>
)}
{onPinView && !isReadonly && (
<DropdownMenuItem
data-testid={`view-tab-menu-pin-${view.id}`}
onClick={() => onPinView(view.id, !view.isPinned)}
>
{view.isPinned
? <><PinOff className="h-4 w-4 mr-2" /> {viewTabLabel('view.unpinView', 'Unpin view')}</>
: <><Pin className="h-4 w-4 mr-2" /> {viewTabLabel('view.pinView', 'Pin view')}</>}
</DropdownMenuItem>
)}
{onChangeViewType && !isReadonly && availableViewTypes && availableViewTypes.length > 0 && (
<DropdownMenuSub>
<DropdownMenuSubTrigger data-testid={`view-tab-menu-change-type-${view.id}`}>
<LayoutGrid className="h-4 w-4 mr-2" /> {viewTabLabel('view.changeViewType', 'Change view type')}
</DropdownMenuSubTrigger>
<DropdownMenuSubContent>
{availableViewTypes.map((vt) => {
const TypeIcon = viewTypeIcons[vt.type] || DefaultIcon;
return (
<DropdownMenuItem
key={vt.type}
data-testid={`view-tab-menu-type-${view.id}-${vt.type}`}
disabled={vt.type === view.type}
onClick={() => onChangeViewType(view.id, vt.type)}
>
<TypeIcon className="h-4 w-4 mr-2" />
<span>{vt.label}</span>
</DropdownMenuItem>
);
})}
</DropdownMenuSubContent>
</DropdownMenuSub>
)}
{onDeleteView && !isReadonly && (
<>
<DropdownMenuSeparator />
<DropdownMenuItem
data-testid={`view-tab-menu-delete-${view.id}`}
onClick={() => onDeleteView(view.id)}
className="text-destructive focus:text-destructive"
>
<Trash2 className="h-4 w-4 mr-2" /> {viewTabLabel('view.deleteView', 'Delete view')}
</DropdownMenuItem>
</>
)}
{onManageViews && (
<>
<DropdownMenuSeparator />
<DropdownMenuItem
data-testid={`view-tab-menu-manage-${view.id}`}
onClick={onManageViews}
>
<ListOrdered className="h-4 w-4 mr-2" /> {viewTabLabel('view.manageAllViews', 'Manage all views…')}
</DropdownMenuItem>
</>
)}
</DropdownMenuContent>
</DropdownMenu>
)}
</div>
);
const wrapWithContextMenu = (tabContent: React.ReactElement) => {
if (!enableContextMenu || isRenaming) return tabContent;
return (
<ContextMenu>
<ContextMenuTrigger asChild>
{tabContent}
</ContextMenuTrigger>
<ContextMenuContent>
{onRenameView && !isReadonly && (
<ContextMenuItem
data-testid={`context-menu-rename-${view.id}`}
onClick={() => startRename(view.id)}
>
<Pencil className="h-4 w-4 mr-2" /> {viewTabLabel('view.rename', 'Rename')}
</ContextMenuItem>
)}
{onDuplicateView && (
<ContextMenuItem
data-testid={`context-menu-duplicate-${view.id}`}
onClick={() => onDuplicateView(view.id)}
>
<Copy className="h-4 w-4 mr-2" /> {viewTabLabel('view.duplicateView', 'Duplicate view')}
</ContextMenuItem>
)}
{onShareView && (
<ContextMenuItem
data-testid={`context-menu-share-${view.id}`}
onClick={() => onShareView(view.id)}
>
<Share2 className="h-4 w-4 mr-2" /> {viewTabLabel('view.shareView', 'Share view')}
</ContextMenuItem>
)}
{onSetDefaultView && !isReadonly && (
<ContextMenuItem
data-testid={`context-menu-default-${view.id}`}
onClick={() => onSetDefaultView(view.id)}
>
<Star className="h-4 w-4 mr-2" /> {viewTabLabel('view.setAsDefault', 'Set as default')}
</ContextMenuItem>
)}
{onPinView && !isReadonly && (
<ContextMenuItem
data-testid={`context-menu-pin-${view.id}`}
onClick={() => onPinView(view.id, !view.isPinned)}
>
{view.isPinned
? <><PinOff className="h-4 w-4 mr-2" /> {viewTabLabel('view.unpinView', 'Unpin view')}</>
: <><Pin className="h-4 w-4 mr-2" /> {viewTabLabel('view.pinView', 'Pin view')}</>
}
</ContextMenuItem>
)}
{onChangeViewType && !isReadonly && availableViewTypes && availableViewTypes.length > 0 && (
<>
<ContextMenuSeparator />
<ContextMenuSub>
<ContextMenuSubTrigger data-testid={`context-menu-change-type-${view.id}`}>
<LayoutGrid className="h-4 w-4 mr-2" /> {viewTabLabel('view.changeViewType', 'Change view type')}
</ContextMenuSubTrigger>
<ContextMenuSubContent data-testid={`context-menu-type-submenu-${view.id}`}>
{availableViewTypes.map((vt) => {
const TypeIcon = viewTypeIcons[vt.type] || DefaultIcon;
return (
<ContextMenuItem
key={vt.type}
data-testid={`context-menu-type-${view.id}-${vt.type}`}
disabled={vt.type === view.type}
onClick={() => onChangeViewType(view.id, vt.type)}
>
<TypeIcon className="h-4 w-4 mr-2" />
<div className="flex flex-col">
<span>{vt.label}</span>
{vt.description && (
<span className="text-xs text-muted-foreground">{vt.description}</span>
)}
</div>
</ContextMenuItem>
);
})}
</ContextMenuSubContent>
</ContextMenuSub>
</>
)}
{onDeleteView && !isReadonly && (
<>
<ContextMenuSeparator />
<ContextMenuItem
data-testid={`context-menu-delete-${view.id}`}
onClick={() => onDeleteView(view.id)}
className="text-destructive focus:text-destructive"
>
<Trash2 className="h-4 w-4 mr-2" /> {viewTabLabel('view.deleteView', 'Delete view')}
</ContextMenuItem>
</>
)}
{onManageViews && (
<>
<ContextMenuSeparator />
<ContextMenuItem
data-testid={`context-menu-manage-${view.id}`}
onClick={onManageViews}
>
<ListOrdered className="h-4 w-4 mr-2" /> {viewTabLabel('view.manageAllViews', 'Manage all views…')}
</ContextMenuItem>
</>
)}
</ContextMenuContent>
</ContextMenu>
);
};
// Build the tab with optional drag-reorder wrapper
if (reorderable && onReorderViews) {
return (
<React.Fragment key={view.id}>
{showSeparator && (
<div data-testid="view-tab-visibility-separator" className="w-px h-5 bg-border mx-1 self-center shrink-0" />
)}
<SortableTab id={view.id}>
{({ setNodeRef, style, listeners, attributes, isDragging }) => (
<div ref={setNodeRef} style={style} className={cn('flex', isDragging && 'z-10')}>
{wrapWithContextMenu(buildTabContent({ listeners, attributes, isDragging }))}
</div>
)}
</SortableTab>
</React.Fragment>
);
}
return (
<React.Fragment key={view.id}>
{showSeparator && (
<div data-testid="view-tab-visibility-separator" className="w-px h-5 bg-border mx-1 self-center shrink-0" />
)}
{wrapWithContextMenu(buildTabContent())}
</React.Fragment>
);
};
const tabList = (
<>
{visibleViews.map((view, index) => renderTab(view, index))}
</>
);
return (
<TooltipProvider>
<div
data-testid="view-tab-bar"
className={cn('flex items-center gap-0.5 -mb-px', className)}
>
{/* Visible tabs — optionally wrapped with DndContext for reorder */}
{reorderable && onReorderViews ? (
<DndContext sensors={sensors} collisionDetection={closestCenter} onDragEnd={handleDragEnd}>
<SortableContext items={visibleViews.map(v => v.id)} strategy={horizontalListSortingStrategy}>
<div data-testid="view-tab-sortable-container" className="flex items-center gap-0.5">
{tabList}
</div>
</SortableContext>
</DndContext>
) : (
tabList
)}
{/* Overflow "More" dropdown */}
{overflowViews.length > 0 && (
<DropdownMenu>
<DropdownMenuTrigger asChild>
<button
data-testid="view-tab-overflow"
className="inline-flex items-center gap-1 px-2 py-2 text-sm text-muted-foreground hover:text-foreground transition-colors"
>
<MoreHorizontal className="h-4 w-4" />
<span className="text-xs">{viewTabLabel('view.moreViews', `${overflowViews.length} more`, { count: overflowViews.length })}</span>
</button>
</DropdownMenuTrigger>
<DropdownMenuContent align="end">
{onManageViews && (
<>
<DropdownMenuItem
data-testid="view-tab-overflow-manage"
onClick={onManageViews}
className="font-medium"
>
<ListOrdered className="h-4 w-4 mr-2" /> {viewTabLabel('view.manageAllViews', 'Manage all views…')}
</DropdownMenuItem>
<DropdownMenuSeparator />
</>
)}
{overflowViews.map((view) => {
const ViewIcon = viewTypeIcons[view.type] || DefaultIcon;
return (
<DropdownMenuItem
key={view.id}
data-testid={`view-tab-overflow-${view.id}`}
onClick={() => onViewChange(view.id)}
>
{view.isPinned && <Pin className="h-3 w-3 mr-1 text-primary shrink-0" />}
<ViewIcon className="h-4 w-4 mr-2" />
{view.label}
{showIndicators && (view.hasActiveFilters || view.hasActiveSort) && (
<span className="ml-auto inline-flex items-center gap-0.5 h-4 px-1 rounded-full bg-primary/10 text-primary">
{view.hasActiveFilters && <FilterIcon className="h-2.5 w-2.5" />}
{view.hasActiveSort && <ArrowUpDown className="h-2.5 w-2.5" />}
</span>
)}
</DropdownMenuItem>
);
})}
</DropdownMenuContent>
</DropdownMenu>
)}
{/* Inline "+" Add View button */}
{showAddButton && onAddView && (
<Tooltip>
<TooltipTrigger asChild>
<button
data-testid="view-tab-add"
onClick={onAddView}
className="inline-flex items-center px-2 py-2 text-muted-foreground hover:text-foreground transition-colors"
>
<Plus className="h-4 w-4" />
</button>
</TooltipTrigger>
<TooltipContent>Add View</TooltipContent>
</Tooltip>
)}
{/* "Save as View" indicator */}
{showSaveAsView && hasUnsavedChanges && (
<div
data-testid="view-tab-save-as"
className="flex items-center gap-1 ml-2 text-xs text-amber-600 dark:text-amber-400"
>
<Save className="h-3.5 w-3.5" />
<span className="hidden sm:inline">Unsaved changes</span>
{onSaveAsView && (
<Button
variant="ghost"
size="sm"
data-testid="view-tab-save-as-btn"
className="h-6 px-2 text-xs"
onClick={onSaveAsView}
>
Save as View
</Button>
)}
{onResetChanges && (
<Button
variant="ghost"
size="sm"
data-testid="view-tab-reset-btn"
className="h-6 px-2 text-xs"
onClick={onResetChanges}
>
Reset
</Button>
)}
</div>
)}
</div>
</TooltipProvider>
);
};