"use client" /** * ListPageTemplate — reusable template for any list-based page. * * Scroll: table / list / board tabs grow with `[data-page-scroll]` (see * `.cursor/rules/exxat-list-page-hub-scroll.mdc`). Folder / panel / tree / dashboard * tabs fill the viewport and scroll internally. * * Provides: page header slot, optional key metrics, tabbed views * (table/list/board/dashboard) with add/remove/configure per-tab, * and an export drawer. * * Usage: * } * metrics={} * defaultTabs={DEFAULT_TABS} * renderContent={(tab) => } * /> * * Connected views (table | list | board | dashboard) must share one `useTableState` * and pass `tableState.rows` into non-table surfaces — see `docs/data-views-pattern.md` * and `AGENTS.md` §4. * * View chrome is shared with `ViewSegmentedControl` / `viewSegmentedToolbarClass` in * `@/components/ui/view-segmented-control` and re-exported from `@/components/data-views`. */ import * as React from "react" import { cn } from "../../lib/utils" import { useRememberedPageScroll } from "../../hooks/use-remembered-page-scroll" import type { DataListViewType } from "../../lib/data-list-view" import { createListPageEditViewHandler, type OpenTablePropertiesHandle, } from "../../lib/list-page-table-properties" import { TABLE_ONLY_HUB_SUPPORTED_VIEWS } from "../../lib/data-list-view-registry" import type { RowHeight } from "../../lib/row-height" import { RenameViewDialog, ReviewViewDialog, ListPageShortcuts, ViewsToolbar, VIEW_TYPES, computeShownViews, resolveExportTotal, resolveSupportedViews, useLatch, useListPageState, useRenameAndReview, useTabActions, useViewsRowFit, } from "./list-page-parts" const ExportDrawer = React.lazy(() => import("../ui/export-drawer").then((m) => ({ default: m.ExportDrawer })), ) // ───────────────────────────────────────────────────────────────────────────── // Types // ───────────────────────────────────────────────────────────────────────────── export type ViewType = DataListViewType /** * Opt-in viewport-fill tab bodies. Empty by default so every hub view * (including folder / panel / tree) grows with `[data-page-scroll]` like table. */ const LIST_PAGE_VIEWPORT_FILL_VIEWS = new Set([]) export { VIEW_TYPES } export interface FilterOption { id: string label: string } export interface ViewTab { id: string label: string viewType: ViewType icon: string /** Optional filter key for lifecycle or category-based filtering */ filterId: string /** * Per-view row density preference captured at creation time (or later via * Properties). Consumers that render tables/boards can read this to set the * initial `rowHeight` for that specific view tab. */ rowHeight?: RowHeight } export interface ListPageTemplateProps { /** Page header — rendered above metrics */ header: React.ReactNode /** Optional metrics strip — rendered below header */ metrics?: React.ReactNode /** * Default visibility for the metrics strip when not controlled. * Persisted under `:listpage:show-metrics:v1` when `persistKey` is set. * @default true */ defaultShowMetrics?: boolean /** Whether to show metrics (controlled externally) */ showMetrics?: boolean /** Called when metrics visibility changes (controlled mode) */ onShowMetricsChange?: (show: boolean) => void /** Initial tabs (uncontrolled mode) */ defaultTabs: ViewTab[] /** * Controlled tabs — when all four are provided, tab state is owned by the parent * (e.g. for localStorage). Otherwise `defaultTabs` + internal state are used. */ tabs?: ViewTab[] onTabsChange?: (tabs: ViewTab[]) => void activeTabId?: string onActiveTabChange?: (id: string) => void /** Filter options per tab (e.g. All, Upcoming, Ongoing, Completed) */ filterOptions?: FilterOption[] /** Label for the filter sub-menu (default: "Filter") */ filterLabel?: string /** Get count for a tab's filter (for badge) */ getTabCount?: (filterId: string) => number /** Render the content for the active tab */ renderContent: (tab: ViewTab, updateTab: (patch: Partial) => void) => React.ReactNode /** Export drawer props */ exportOpen?: boolean onExportOpenChange?: (open: boolean) => void /** Row count for export; if omitted, uses `getTabCount(activeTab.filterId)` when provided */ exportTotalRows?: number /** * Tab menu — “Edit” (e.g. open table properties). Parent can switch to table view first, then call ref. * Overrides `tablePropertiesRef` when both are set. */ onEditView?: (tab: ViewTab, helpers: { updateTab: (patch: Partial) => void }) => void /** * Ref to the active tab’s table surface (`openPropertiesDrawer`). Wires “View → Edit” to * `TablePropertiesDrawer` when `onEditView` is omitted. */ tablePropertiesRef?: React.RefObject /** When true, hide the views tab strip (tabs + add view) — e.g. search landing with a single table surface. */ hideViewsToolbar?: boolean /** * Subset of view types the hub actually implements (e.g. List hub omits Dashboard/Folder). * When set, the Add view menu and ⌘1–9 shortcuts are filtered so users cannot add a view the * hub cannot render. When omitted, defaults to {@link TABLE_ONLY_HUB_SUPPORTED_VIEWS} * (table only). Pass {@link FULL_HUB_SUPPORTED_VIEWS} when the product asks for Add view parity. * (table, list, board, dashboard). Pass an explicit allowlist for specialized hubs * (e.g. tokens table-only, library with folder/calendar). * * Pair with `TablePropertiesDrawerButton.supportedViewTypes` to keep Properties consistent. */ supportedViewTypes?: readonly DataListViewType[] /** * **Opt-in localStorage persistence** for the page-level state: the * user's view tabs (their labels, view types, icons, filterIds) and the * currently active tab. When set, returning to the hub restores the * tab arrangement. * * Storage keys: `exxat-ds::listpage:tabs:v1` and * `exxat-ds::listpage:active-tab:v1`. **Use the same key * across renders** of the same hub or persistence will reset. * * When `tabs` / `activeTabId` are also passed in controlled mode, the * controlled props win — `persistKey` is ignored. Most hubs SHOULD pick * one or the other. * * @see `apps/web/docs/persisted-state-pattern.md` * @see `.cursor/rules/exxat-persisted-state.mdc` */ persistKey?: string /** * Whether count badges should be shown in the view tab bar. * This is a **hub-level** preference (affects all tabs). * When `persistKey` is provided and the prop is not controlled, the value * is persisted under `:listpage:show-view-counts:v1`. */ showViewCounts?: boolean onShowViewCountsChange?: (show: boolean) => void /** * Called when the user selects a view type from the "Add view" picker. * The parent (HubTable / LibraryTable) is expected to open * `TablePropertiesDrawer` in creation mode (`isCreatingNewView`) for that type, * allowing the user to set name + relevant initial view settings before the * tab is actually created. */ onRequestCreateView?: (type: ViewType) => void } // ───────────────────────────────────────────────────────────────────────────── // Component // ───────────────────────────────────────────────────────────────────────────── function ListPageTabBody({ tab, renderContent, updateTab, }: { tab: ViewTab renderContent: (tab: ViewTab, updateTab: (patch: Partial) => void) => React.ReactNode updateTab: (id: string, patch: Partial) => void }) { return <>{renderContent(tab, patch => updateTab(tab.id, patch))} } function ListPageExport({ exportMounted, onExportOpenChange, exportOpen, totalRows, }: { exportMounted: boolean onExportOpenChange: ((open: boolean) => void) | undefined exportOpen: boolean totalRows: () => number }) { if (!onExportOpenChange || !exportMounted) return null return ( ) } function ListPageViewBody({ activeTab, fillsViewport, renderContent, updateTab, }: { activeTab: ViewTab | undefined fillsViewport: boolean renderContent: ListPageTemplateProps["renderContent"] updateTab: (id: string, patch: Partial) => void }) { if (!activeTab) return null return (
) } function ListPageMetricsSlot({ show, metrics, }: { show: boolean metrics: React.ReactNode }) { if (!show || !metrics) return null /* Above the views toolbar so KPI chart tooltips are not covered while metrics are on-screen. */ return
{metrics}
} function ListPageHeaderSlot({ header }: { header: React.ReactNode }) { if (!header) return null return
{header}
} /** * When a hub declares the views it implements, both the Add view menu and ⌘1–9 shortcut * bindings are filtered to that subset so unsupported views are never offered. Without * this, a user could ⌘1 → Dashboard into a hub that cannot render it (would show the * not-configured empty state). Memoized because it filters on every render path. */ function useAddableViewTypes( supportedViewTypes: readonly DataListViewType[] | undefined, ) { return React.useMemo(() => { const allowed = new Set( resolveSupportedViews(supportedViewTypes, TABLE_ONLY_HUB_SUPPORTED_VIEWS), ) return VIEW_TYPES.filter(v => allowed.has(v.type)) }, [supportedViewTypes]) } export function ListPageTemplate({ header, metrics, defaultShowMetrics = true, showMetrics: showMetricsProp, onShowMetricsChange, defaultTabs, tabs: tabsProp, onTabsChange, activeTabId: activeTabIdProp, onActiveTabChange, getTabCount, renderContent, exportOpen = false, onExportOpenChange, exportTotalRows = 0, onEditView, tablePropertiesRef, hideViewsToolbar = false, supportedViewTypes, persistKey, showViewCounts: showViewCountsProp, onShowViewCountsChange, onRequestCreateView, }: ListPageTemplateProps) { const exportMounted = useLatch(exportOpen) const addableViewTypes = useAddableViewTypes(supportedViewTypes) const { tabs, setTabsState, activeTabId, setActiveTabId, showViewCounts, showMetrics } = useListPageState({ defaultTabs, tabsProp, onTabsChange, activeTabIdProp, onActiveTabChange, persistKey, showViewCountsProp, onShowViewCountsChange, showMetricsProp, onShowMetricsChange, defaultShowMetrics, }) const { addView, removeTab, updateTab, duplicateTab } = useTabActions( tabs, activeTabId, setTabsState, setActiveTabId, ) const review = useRenameAndReview(updateTab) const activeTab = tabs.find(t => t.id === activeTabId) ?? tabs[0] /** * Views share the page scrollport and have wildly different lengths — a table * of 400 rows, a dashboard of four charts — so each keeps its own place rather * than inheriting an offset that means nothing in the view being opened. */ const [root, setRoot] = React.useState(null) useRememberedPageScroll(activeTab?.id, { node: root, panelSelector: '[data-slot="list-page-view-body"]', }) const tabBodyFillsViewport = Boolean( activeTab && LIST_PAGE_VIEWPORT_FILL_VIEWS.has(activeTab.viewType), ) /** Hide lifecycle/Add-view toolbar when table-only + single tab (opt-in multi-view). */ const showViewsToolbar = !hideViewsToolbar && (tabs.length > 1 || resolveSupportedViews(supportedViewTypes, TABLE_ONLY_HUB_SUPPORTED_VIEWS).length > 1) const { viewsViewportRef, openViewLabels, visibleViewCount } = useViewsRowFit( tabs.length, showViewsToolbar, ) const { canShedViews, shownViews, hiddenViews } = computeShownViews( tabs, activeTabId, showViewsToolbar, visibleViewCount, ) const editViewFromRef = React.useMemo( () => (tablePropertiesRef ? createListPageEditViewHandler(tablePropertiesRef) : undefined), [tablePropertiesRef] ) const resolvedOnEditView = onEditView ?? editViewFromRef const actions = { addView, removeTab, updateTab, duplicateTab, openRename: review.openRename, openReview: review.openReview, } return ( <> {/* Block wrapper (not a flex column): sticky view tabs must not be flex items of `PrimaryPageTemplate`'s content column — stretch/overflow interactions made Tokens and other hubs lose sticky while Library looked fine. */}
{/* ── Views toolbar (not tablist: settings/close are not tabs — WCAG 1.3.1 / ARIA) ── */} {showViewsToolbar ? ( ) : null} {/* ── Content — keyed by tab so each view tab owns its height (no stale min-height). Page-scroll views (table / list / board) grow with `[data-page-scroll]`. Viewport-fill views (folder / panel / tree / dashboard) use flex-1 + internal pane scroll. ── */} {/* ── Export ──────────────────────────────────────────────── */} resolveExportTotal(exportTotalRows, getTabCount, activeTab)} /> review.setReviewOpen(false)} getTabCount={getTabCount} />
) }