"use client" /** * Internal building blocks for `ListPageTemplate` — state hooks, pure helpers * and the views-toolbar / dialog sub-components. Split out so the template * itself stays a thin composition; nothing here is part of the public API. */ import * as React from "react" import { cn } from "../../lib/utils" import { horizontalPadding, measureRowLabels, naturalRowWidth, useRowFitLadder, type RowFitMeasurement, } from "../../hooks/use-row-fit-ladder" import { Tip } from "../ui/tip" import { Button } from "../ui/button" import { HorizontalScrollRegion } from "../ui/horizontal-scroll-region" import { Input } from "../ui/input" import { Dialog, DialogContent, DialogDescription, DialogFooter, DialogHeader, DialogTitle, } from "../ui/dialog" import { DropdownMenu, DropdownMenuContent, DropdownMenuItem, DropdownMenuLabel, DropdownMenuSeparator, DropdownMenuTrigger, DropdownMenuRadioGroup, DropdownMenuRadioItem, Shortcut, } from "../ui/dropdown-menu" import { DATA_LIST_VIEW_TILES, dataListViewAddShortcut, type DataListViewType, } from "../../lib/data-list-view" import { viewSegmentedToolbarClass, viewSegmentedButtonClass, } from "../ui/view-segmented-control" import { usePersistedState } from "../../lib/persisted-state" import type { ViewTab, ViewType } from "./list-page" type TabPatch = Partial type OnEditView = ( tab: ViewTab, helpers: { updateTab: (patch: TabPatch) => void }, ) => void /** Same labels/icons as Properties drawer `SelectionTileGrid` — single source in `DATA_LIST_VIEW_TILES`. */ export const VIEW_TYPES: { type: ViewType; label: string; icon: string }[] = DATA_LIST_VIEW_TILES.map(t => ({ type: t.value, label: t.label, icon: t.icon, })) /** Collision-proof id for a dynamically-added tab. Module-level counters reset * on HMR while React state survives, so we derive from a timestamp + random. */ function makeTabId(type: string): string { const rand = Math.random().toString(36).slice(2, 8) return `${type}-${Date.now().toString(36)}-${rand}` } /** * Wraps a control in a `Tip` only when there is something the control is not * already saying. A tab showing its label does not need a tooltip repeating it. */ function withTip(control: React.ReactElement, label: string | null) { if (!label) return control return ( {control} ) } const COUNT_BADGE_PALETTES: Record = { all: { active: "bg-slate-600 text-white dark:bg-slate-500", inactive: "bg-slate-100 text-slate-800 dark:bg-slate-800/70 dark:text-slate-100", }, upcoming: { active: "bg-amber-600 text-white", inactive: "bg-amber-100 text-amber-950 dark:bg-amber-950/45 dark:text-amber-100", }, ongoing: { active: "bg-blue-600 text-white", inactive: "bg-blue-100 text-blue-950 dark:bg-blue-950/45 dark:text-blue-100", }, completed: { active: "bg-emerald-600 text-white", inactive: "bg-emerald-100 text-emerald-950 dark:bg-emerald-950/45 dark:text-emerald-100", }, } /** Count pill on the views toolbar — color by lifecycle/status filter (WCAG: dark text on light inactive; light text on solid active). */ export function viewToolbarCountBadgeClass(filterId: string, isActive: boolean): string { const p = COUNT_BADGE_PALETTES[filterId] ?? COUNT_BADGE_PALETTES.all return isActive ? p.active : p.inactive } function viewTypeLabel(viewType: ViewType) { return VIEW_TYPES.find(v => v.type === viewType)?.label } // ───────────────────────────────────────────────────────────────────────────── // Pure helpers // ───────────────────────────────────────────────────────────────────────────── function storageKeyFor( persistKey: string | undefined, enabled: boolean, suffix: string, ) { return persistKey && enabled ? `${persistKey}:listpage:${suffix}:v1` : "" } function resolveFlag( controlledValue: boolean | undefined, storageKey: string, internal: boolean, fallback: boolean, ) { if (controlledValue !== undefined) return controlledValue return storageKey ? internal : fallback } export function resolveSupportedViews( supportedViewTypes: readonly DataListViewType[] | undefined, fallback: readonly DataListViewType[], ) { return supportedViewTypes && supportedViewTypes.length > 0 ? supportedViewTypes : fallback } function splitViews( tabs: ViewTab[], activeTabId: string, canShedViews: boolean, visibleViewCount: number, ) { if (!canShedViews || visibleViewCount >= tabs.length) { return { shownViews: tabs, hiddenViews: [] as ViewTab[] } } let shownViews = tabs.slice(0, visibleViewCount) let hiddenViews = tabs.slice(visibleViewCount) const activeView = activeTabId ? hiddenViews.find(t => t.id === activeTabId) : undefined const activeIsShown = shownViews.some(t => t.id === activeTabId) if (activeView && !activeIsShown) { shownViews = [...shownViews.slice(0, -1), activeView] const onRow = new Set(shownViews.map(t => t.id)) hiddenViews = tabs.filter(t => !onRow.has(t.id)) } return { shownViews, hiddenViews } } export function computeShownViews( tabs: ViewTab[], activeTabId: string, showViewsToolbar: boolean, visibleViewCount: number, ) { const canShedViews = showViewsToolbar && tabs.length > 1 return { canShedViews, ...splitViews(tabs, activeTabId, canShedViews, visibleViewCount), } } function tabsAfterRemove(prev: ViewTab[], id: string, activeTabId: string) { const next = prev.filter(t => t.id !== id) if (activeTabId !== id || next.length === 0) return { next, nextActive: null } const idx = Math.max(0, prev.findIndex(t => t.id === id) - 1) return { next, nextActive: next[Math.min(idx, next.length - 1)].id } } function newViewTab(type: ViewType, tabs: ViewTab[]): ViewTab { const def = VIEW_TYPES.find(d => d.type === type)! const count = tabs.filter(t => t.viewType === type).length const label = count === 0 ? def.label : `${def.label} ${count + 1}` return { id: makeTabId(type), label, viewType: type, icon: def.icon, filterId: "all", } } function duplicatedTab(tab: ViewTab): ViewTab { return { id: makeTabId(tab.viewType), label: `Copy of ${tab.label}`, viewType: tab.viewType, icon: tab.icon, filterId: tab.filterId, rowHeight: tab.rowHeight, } } export function resolveExportTotal( exportTotalRows: number | undefined, getTabCount: ((filterId: string) => number) | undefined, activeTab: ViewTab, ) { return exportTotalRows ?? getTabCount?.(activeTab.filterId) ?? 0 } // ───────────────────────────────────────────────────────────────────────────── // Hooks // ───────────────────────────────────────────────────────────────────────────── /** True once `on` has been true — set during render, like the original inline latch. */ export function useLatch(on: boolean) { const [latched, setLatched] = React.useState(false) if (on && !latched) setLatched(true) return latched } type StateInput = { defaultTabs: ViewTab[] tabsProp?: ViewTab[] onTabsChange?: (tabs: ViewTab[]) => void activeTabIdProp?: string onActiveTabChange?: (id: string) => void persistKey?: string showViewCountsProp?: boolean onShowViewCountsChange?: (show: boolean) => void showMetricsProp?: boolean onShowMetricsChange?: (show: boolean) => void defaultShowMetrics: boolean } /** * Internal tabs/active-tab state, optionally backed by `localStorage` when * `persistKey` is set AND the consumer is NOT in controlled mode. * `usePersistedState` accepts an empty key as "disabled, behave like useState", * so it is always called once (rules of hooks) and storage is toggled by the * key string. Hubs that move forward between versions of `defaultTabs` should * bump `persistKey`. */ export function useListPageState(input: StateInput) { const { defaultTabs, tabsProp, onTabsChange, activeTabIdProp, onActiveTabChange } = input const controlled = [tabsProp, onTabsChange, activeTabIdProp, onActiveTabChange].every( v => v !== undefined, ) const { persistKey } = input const countsUncontrolled = input.showViewCountsProp === undefined && input.onShowViewCountsChange === undefined const metricsUncontrolled = input.showMetricsProp === undefined && input.onShowMetricsChange === undefined const tabsStorageKey = storageKeyFor(persistKey, !controlled, "tabs") const activeStorageKey = storageKeyFor(persistKey, !controlled, "active-tab") const showCountsStorageKey = storageKeyFor(persistKey, countsUncontrolled, "show-view-counts") const metricsStorageKey = storageKeyFor(persistKey, metricsUncontrolled, "show-metrics") const [internalTabs, setInternalTabs] = usePersistedState( tabsStorageKey, defaultTabs, ) const [internalActiveId, setInternalActiveId] = usePersistedState( activeStorageKey, defaultTabs[0]?.id ?? "", ) // Hub-level "show counts in the tab bar" — default: show counts. const [internalShowViewCounts] = usePersistedState(showCountsStorageKey, true) const [internalShowMetrics] = usePersistedState( metricsStorageKey, input.defaultShowMetrics, ) const tabs = controlled ? (tabsProp as ViewTab[]) : internalTabs const setTabsState = React.useCallback( (action: React.SetStateAction) => { if (!controlled) return setInternalTabs(action) const current = tabsProp as ViewTab[] const next = typeof action === "function" ? action(current) : action ;(onTabsChange as (tabs: ViewTab[]) => void)(next) }, [controlled, onTabsChange, tabsProp, setInternalTabs], ) const activeTabId = controlled ? (activeTabIdProp as string) : internalActiveId const setActiveTabId = controlled ? (onActiveTabChange as (id: string) => void) : setInternalActiveId return { tabs, setTabsState, activeTabId, setActiveTabId, showViewCounts: resolveFlag( input.showViewCountsProp, showCountsStorageKey, internalShowViewCounts, true, ), showMetrics: resolveFlag( input.showMetricsProp, metricsStorageKey, internalShowMetrics, input.defaultShowMetrics, ), } } /** * Prices rung 1 for the views row, the same way `Tabs` does for a tablist. * Without this the row only knows how to trade *every* inactive label for its * icon at once, so a row a few pixels short read as a row of glyphs — and, * because the all-or-nothing rung records the width it failed at, it stayed * that way even after the row had room again. */ export function useViewsRowFit(tabCount: number, enabled: boolean) { const viewsViewportRef = React.useRef(null) const measureViewsRow = React.useCallback((): RowFitMeasurement | null => { const viewport = viewsViewportRef.current const content = viewport?.firstElementChild as HTMLElement | null if (!viewport || !content) return null return { available: viewport.clientWidth - horizontalPadding(viewport), // The toolbar clamps the same way the row does, so sum it rather than // measure it. content: naturalRowWidth(content, "[data-slot='view-segmented-toolbar']"), labels: measureRowLabels( content, label => label.dataset.viewTabPinned === "true", ), } }, []) const { openLabels, visible } = useRowFitLadder({ viewportRef: viewsViewportRef, count: tabCount, // A lone view has nothing to compare its glyph against, and it is the // selected one anyway — never worth reducing to an icon. canCollapse: tabCount > 1, enabled, measure: measureViewsRow, }) return { viewsViewportRef, openViewLabels: openLabels, visibleViewCount: visible } } export function useTabActions( tabs: ViewTab[], activeTabId: string, setTabsState: (action: React.SetStateAction) => void, setActiveTabId: (id: string) => void, ) { function addView(type: ViewType) { const newTab = newViewTab(type, tabs) setTabsState(prev => [...prev, newTab]) setActiveTabId(newTab.id) } function removeTab(id: string, e: React.MouseEvent | React.KeyboardEvent) { e.stopPropagation() setTabsState(prev => { const { next, nextActive } = tabsAfterRemove(prev, id, activeTabId) if (nextActive !== null) setActiveTabId(nextActive) return next }) } function updateTab(id: string, patch: TabPatch) { setTabsState(prev => prev.map(t => (t.id === id ? { ...t, ...patch } : t))) } function duplicateTab(tab: ViewTab) { const newTab = duplicatedTab(tab) setTabsState(prev => [...prev, newTab]) setActiveTabId(newTab.id) } return { addView, removeTab, updateTab, duplicateTab } } export function useRenameAndReview(updateTab: (id: string, patch: TabPatch) => void) { const [renameOpen, setRenameOpen] = React.useState(false) const [renameValue, setRenameValue] = React.useState("") const renameTabIdRef = React.useRef(null) const [reviewOpen, setReviewOpen] = React.useState(false) const [reviewTab, setReviewTab] = React.useState(null) function openRename(tab: ViewTab) { renameTabIdRef.current = tab.id setRenameValue(tab.label) setRenameOpen(true) } function commitRename() { const tabId = renameTabIdRef.current if (!tabId) return const v = renameValue.trim() if (v) updateTab(tabId, { label: v }) setRenameOpen(false) renameTabIdRef.current = null } function openReview(tab: ViewTab) { setReviewTab(tab) setReviewOpen(true) } function onReviewOpenChange(open: boolean) { setReviewOpen(open) if (!open) setReviewTab(null) } return { renameOpen, setRenameOpen, renameValue, setRenameValue, openRename, commitRename, reviewOpen, setReviewOpen, reviewTab, openReview, onReviewOpenChange, } } // ───────────────────────────────────────────────────────────────────────────── // Shortcuts // ───────────────────────────────────────────────────────────────────────────── function AddViewShortcuts({ viewTypes, onAdd, }: { viewTypes: { type: ViewType }[] onAdd: (type: ViewType) => void }) { return ( <> {viewTypes.slice(0, 9).map((v, i) => ( onAdd(v.type)} /> ))} ) } function AddViewShortcut({ index, onInvoke, }: { index: number onInvoke: () => void }) { const keys = dataListViewAddShortcut(index) if (!keys) return null return } export type TabActions = { addView: (type: ViewType) => void removeTab: (id: string, e: React.MouseEvent | React.KeyboardEvent) => void updateTab: (id: string, patch: TabPatch) => void duplicateTab: (tab: ViewTab) => void openRename: (tab: ViewTab) => void openReview: (tab: ViewTab) => void } export function ListPageShortcuts({ show, addableViewTypes, activeTab, tabCount, onEditView, actions, }: { show: boolean addableViewTypes: { type: ViewType }[] activeTab: ViewTab | undefined tabCount: number onEditView: OnEditView | undefined actions: TabActions }) { if (!show) return null return ( <> {activeTab ? ( ) : null} ) } function ActiveTabShortcuts({ activeTab, tabCount, onEditView, actions, }: { activeTab: ViewTab tabCount: number onEditView: OnEditView | undefined actions: TabActions }) { return ( <> actions.openRename(activeTab)} /> onEditView?.(activeTab, { updateTab: p => actions.updateTab(activeTab.id, p), }) } /> actions.duplicateTab(activeTab)} /> actions.openReview(activeTab)} /> actions.removeTab(activeTab.id, e as unknown as React.KeyboardEvent)} /> ) } // ───────────────────────────────────────────────────────────────────────────── // Views toolbar // ───────────────────────────────────────────────────────────────────────────── function ViewTabCount({ show, count, filterId, isActive, }: { show: boolean count: number | undefined filterId: string isActive: boolean }) { if (!show || count === undefined) return null return ( {count} ) } const COLLAPSED_LABEL_CLASSES = [ "grid-cols-[0fr]", "opacity-0", // The button's own `gap-1.5` outlives a zero-width label, // so hand it back: a collapsed tab is its icon, not its // icon and a gap. "-ms-1.5", ] function ViewTabInner({ tab, isActive, iconOnly, count, showViewCounts, }: { tab: ViewTab isActive: boolean iconOnly: boolean count: number | undefined showViewCounts: boolean }) { return ( <>