Skip to content

Latest commit

Β 

History

History
523 lines (422 loc) Β· 16.7 KB

README.md

File metadata and controls

523 lines (422 loc) Β· 16.7 KB

Tab Package

Overview

The /cmp/tab/ package provides Hoist's tabbed interface system - components and models for organizing content into switchable views. The system supports routing integration, lazy rendering, smart refresh strategies, nested tab containers, and dynamic (user-configurable) tabs.

Platform-specific TabContainer components in /desktop/cmp/tab/ and /mobile/cmp/tab/ render the tab UI while sharing the cross-platform models defined here.

Architecture

TabContainerModel
β”œβ”€β”€ tabs: TabModel[]              # Child tabs
β”œβ”€β”€ activeTabId: string           # Currently active tab ID
β”œβ”€β”€ route: string                 # Base route for routing (desktop only)
β”œβ”€β”€ renderMode: RenderMode        # Default render strategy for tabs
β”œβ”€β”€ refreshMode: RefreshMode      # Default refresh strategy for tabs
β”œβ”€β”€ refreshContextModel           # RefreshContext for coordinated refresh
β”œβ”€β”€ dynamicTabSwitcherModel       # For user-configurable tabs
└── Methods: setActiveTabId(), activateTab(), addTab(), removeTab(), setTabs()

TabModel
β”œβ”€β”€ id: string                    # Unique identifier
β”œβ”€β”€ title: ReactNode              # Tab button text
β”œβ”€β”€ icon: ReactElement            # Tab button icon
β”œβ”€β”€ content: Content              # Tab body content
β”œβ”€β”€ disabled: boolean             # Prevent activation
β”œβ”€β”€ renderMode / refreshMode      # Per-tab overrides
β”œβ”€β”€ childContainerModel           # For nested tab containers
└── Methods: activate(), setDisabled()

TabContainerModel

The main model for configuring and managing a tabbed interface.

Basic Usage

import {TabContainerModel} from '@xh/hoist/cmp/tab';
import {tabContainer} from '@xh/hoist/desktop/cmp/tab';  // or mobile

const tabModel = new TabContainerModel({
    tabs: [
        {id: 'overview', title: 'Overview', content: () => overviewPanel()},
        {id: 'details', title: 'Details', content: () => detailsPanel()},
        {id: 'history', title: 'History', content: () => historyPanel()}
    ],
    defaultTabId: 'overview'
});

// Render
tabContainer({model: tabModel})

Configuration

Property Type Description
tabs TabConfig[] Tab definitions
defaultTabId string Initial active tab (defaults to first tab)
route string Base route for URL routing (desktop only)
restoreTabRouteParams boolean Restore a tab's own route params on return (default: true)
renderMode RenderMode When to render tab content (default: 'lazy')
refreshMode RefreshMode When to refresh tab content (default: 'onShowLazy')
track boolean Track tab views in activity log
switcher TabSwitcherConfig Tab switcher behavior (default: {mode: 'static'})
persistWith PersistOptions Persistence configuration
emptyText ReactNode Placeholder when no tabs

Routing (Desktop Only)

Enable URL-based tab navigation by connecting TabContainerModel to routes defined in your AppModel.

Routes must be defined centrally in AppModel's getRoutes() - the route property on TabContainerModel refers to a route name, and tab IDs must match child route names:

// In AppModel - define route hierarchy
override getRoutes() {
    return [{
        name: 'default',
        path: '/app',
        children: [
            {name: 'overview', path: '/overview'},
            {name: 'reports', path: '/reports', children: [
                {name: 'daily', path: '/daily'},
                {name: 'weekly', path: '/weekly'}
            ]}
        ]
    }];
}

// TabContainerModel - route property references route name, tab IDs match child route names
@managed tabModel = new TabContainerModel({
    route: 'default',  // Matches route name above
    tabs: [
        {id: 'overview', content: overviewPanel},  // ID matches route name
        {
            id: 'reports',  // ID matches route name
            content: {
                tabs: [
                    {id: 'daily', content: dailyReport},   // ID matches nested route name
                    {id: 'weekly', content: weeklyReport}
                ]
            }
        }
    ]
});
// URLs: /app/overview, /app/reports/daily, /app/reports/weekly

When the user switches tabs, the container carries over only the route params declared by its own route or that route's ancestors. Params declared by a tab's route (or its descendants) belong to that tab and are never passed to its siblings - declare any param that tabs should share on a parent route.

Each tab's last route - including any child route and its params - is remembered and restored when the user switches back to it via the container. Memory is discarded if a shared path param has since changed (e.g. /book/:bookId), so one book's selection never reappears under another. Set restoreTabRouteParams: false to return to the tab's bare route instead. Note that navigating explicitly to a tab's bare route (e.g. via XH.navigate()) resets its memory.

See the built-in Admin console (/admin/AppModel.ts) or Toolbox app for complete examples of routed tab hierarchies.

Render Modes

Control when tab content is mounted:

Mode Description
'lazy' Mount on first activation, keep mounted (default)
'always' Mount all tabs immediately
'unmountOnHide' Mount on activation, unmount when hidden
const tabModel = new TabContainerModel({
    renderMode: 'lazy',  // Container default
    tabs: [
        {id: 'light', content: lightPanel},
        {id: 'heavy', content: heavyPanel, renderMode: 'unmountOnHide'}  // Per-tab override
    ]
});

Refresh Modes

Control when tab content is refreshed:

Mode Description
'onShowLazy' Refresh on show, skip if not stale (default)
'onShowAlways' Refresh every time tab is shown
'onLoadAlways' Refresh on load and every show
'never' Only refresh when explicitly requested
const tabModel = new TabContainerModel({
    refreshMode: 'onShowLazy',
    tabs: [
        {id: 'dashboard', content: dashboard, refreshMode: 'onShowAlways'},
        {id: 'settings', content: settings, refreshMode: 'never'}
    ]
});

Tab Navigation

// Activate by ID
tabModel.setActiveTabId('details');

// Sequential navigation
tabModel.activateNextTab();
tabModel.activatePrevTab();
tabModel.activateNextTab(true);  // Cycle to first if at end

// Read active state
tabModel.activeTabId;   // 'overview'
tabModel.activeTab;     // TabModel instance
tabModel.nextTab;       // Next enabled tab
tabModel.prevTab;       // Previous enabled tab

Dynamic Tabs

Add, remove, and modify tabs at runtime:

// Add a tab
tabModel.addTab({
    id: 'newTab',
    title: 'New Tab',
    content: () => newTabPanel()
}, {
    index: 2,                 // Insert position
    activateImmediately: true // Activate after adding
});

// Remove a tab
tabModel.removeTab('newTab');
tabModel.removeTab(tabModel.findTab('newTab'));

// Update tab title
tabModel.setTabTitle('details', 'User Details');

// Replace all tabs
tabModel.setTabs(newTabs);

User-Configurable Tabs (Dynamic Switcher) - Desktop Only

The dynamic switcher enables users to customize their tab bar:

  • Drag-and-drop reordering - Users can reorder tabs by dragging
  • Favorites - Mark frequently-used tabs for quick access
  • Overflow handling - Smooth horizontal scrolling when tabs exceed available width
  • Persistence - Tab order and favorites persist across sessions

Recommended for any tab container, especially an app's primary navigation container, where a non-trivial number of tabs are available and/or some users might focus on particular tabs but not need others.

const tabModel = new TabContainerModel({
    switcher: {mode: 'dynamic'},  // or {mode: 'static'} (default)
    tabs: [...],
    persistWith: {
        localStorageKey: 'tabs',
        persistFavoriteTabIds: true
    }
});

Overflowing Tabs (Static Switcher) - Desktop Only

Set enableOverflow when a static switcher may hold more tabs than fit. Its tab strip then scrolls, and tabs scrolled more than a quarter out of view are also listed in a menu at the end of the switcher. enableOverflow is a prop of the switcher component, so pass it through the switcher prop of tabContainer, not the switcher config of TabContainerModel:

tabContainer({
    model: tabModel,
    switcher: {orientation: 'top', enableOverflow: true}
})

Tabs overflow only when something stops the switcher from growing to fit them, such as its container or a maxWidth on the switcher (maxHeight for a left / right switcher).

When the active tab changes, the switcher scrolls its tab strip by the smallest distance that shows the tab. A scrolling panel or page around the switcher never moves.

Grouped Tabs (Vertical Switchers) - Desktop Only

Long left / right switcher rails can be broken up with display-only group headers. Assign a group key to each tab, and optionally provide titles and icons via switcher.groups - a group without an entry there uses its key as its title.

const tabModel = new TabContainerModel({
    switcher: {
        mode: 'static',
        groups: [
            {key: 'forms', title: 'Forms'},
            {key: 'inputs', title: 'Inputs', icon: Icon.edit()}
        ]
    },
    tabs: [
        {id: 'overview', content: overviewPanel},  // Ungrouped - no header
        {id: 'form', group: 'forms', content: formPanel},
        {id: 'toolbarForms', group: 'forms', content: toolbarFormPanel},
        {id: 'textInput', group: 'inputs', content: textInputPanel},
        {id: 'select', group: 'inputs', content: selectPanel}
    ]
});

Tabs render in their declared order, with a header emitted wherever the group changes - so declare grouped tabs contiguously. Ungrouped tabs can appear anywhere; one that follows a grouped run is set off by a small gap. Headers are not tabs: they are not focusable or routable, and arrow-key navigation and activateNextTab() / activatePrevTab() skip over them. When enableOverflow is set, overflowed tabs are grouped under matching dividers in the overflow menu.

Horizontal (top / bottom) switchers, the dynamic switcher, and mobile ignore groups. Style headers via the --xh-tab-switcher-vertical-group-* CSS variables. By default headers are minimal text labels, with a rule line above each group after the first. For a bolder look, give headers a background and drop the rule:

.my-switcher {
  --xh-tab-switcher-vertical-group-header-bg: var(--xh-orange);
  --xh-tab-switcher-vertical-group-header-text-color: white;
  --xh-tab-switcher-vertical-group-border: none;
  --xh-tab-switcher-vertical-group-gap: var(--xh-spacing-half);
}

Persistence

Persist active tab and/or favorite tabs:

const tabModel = new TabContainerModel({
    tabs: [...],
    persistWith: {
        localStorageKey: 'mainTabs',
        persistActiveTabId: true,        // Remember last active tab
        persistFavoriteTabIds: true      // For dynamic switcher
    }
});

Note: persistActiveTabId and route cannot both be used - routing takes precedence.

TabModel

Configuration for individual tabs within a container.

TabConfig Properties

Property Type Description
id string Unique identifier (required)
title ReactNode Display title (defaults to startCase of id)
icon ReactElement Icon for tab button
tooltip ReactNode Tooltip on hover
disabled boolean Prevent activation
excludeFromSwitcher boolean Hide from UI but allow programmatic/routed access
showRemoveAction boolean Show close button (desktop only)
group string Group key - see Grouped Tabs
content Content Tab body - function, element, or nested tabs
renderMode RenderMode Override container's render mode
refreshMode RefreshMode Override container's refresh mode
omit boolean | () => boolean Conditionally exclude tab

Content Types

// Function returning content (recommended for lazy rendering)
{id: 'panel', content: () => myPanel()}

// Direct element
{id: 'static', content: myStaticElement}

// Nested tab container (array shorthand)
{
    id: 'reports',
    content: [
        {id: 'daily', content: dailyReport},
        {id: 'weekly', content: weeklyReport}
    ]
}

// Nested tab container (explicit config)
{
    id: 'reports',
    content: {
        tabs: [...],
        renderMode: 'unmountOnHide'
    }
}

TabModel Methods

const tab = tabModel.findTab('details');

// Activate this tab
tab.activate();

// Check state
tab.isActive;   // boolean
tab.disabled;   // boolean

// Enable/disable
tab.setDisabled(true);

// Update appearance (direct assignment calls underlying @bindable setter)
tab.title = 'New Title';
tab.icon = Icon.check();

Refresh Integration

TabContainer integrates with Hoist's refresh system via RefreshContextModel:

class MyTabPanelModel extends HoistModel {
    override async doLoadAsync(loadSpec: LoadSpec) {
        // Called based on tab's refreshMode
        const data = await XH.fetchJson({url: 'api/data'}, {loadSpec});
        this.setData(data);
    }
}

// In TabContainer config
{
    id: 'panel',
    content: () => myTabPanel(),
    refreshMode: 'onShowLazy'  // Refresh when shown if stale
}

The tab's refreshContextModel coordinates with the container's context for cascading refresh.

Common Patterns

Tab Container in a Model

class AppModel extends HoistModel {
    @managed tabModel = new TabContainerModel({
        tabs: [
            {id: 'dashboard', title: 'Dashboard', icon: Icon.home(), content: dashboardPanel},
            {id: 'reports', title: 'Reports', icon: Icon.chartLine(), content: reportsPanel},
            {id: 'settings', title: 'Settings', icon: Icon.gear(), content: settingsPanel}
        ],
        track: true,
        persistWith: {localStorageKey: 'mainTabs'}
    });
}

Conditional Tabs

const tabModel = new TabContainerModel({
    tabs: [
        {id: 'overview', content: overview},
        {
            id: 'manage',
            content: managementPanel,
            omit: () => !XH.getUser().hasRole('MANAGER')
        },
        {
            id: 'debug',
            content: debugPanel,
            omit: XH.environmentService.isProduction
        }
    ]
});

Tabs with Dynamic Titles

Tab titles can be any ReactNode. For reactive titles (e.g., with badges that update), use a reaction to update the title when the underlying data changes:

// In your model constructor
this.addReaction({
    track: () => this.alertCount,
    run: count => {
        const alertsTab = this.tabModel.findTab('alerts');
        alertsTab.title = count > 0
            ? span('Alerts ', badge({children: count, intent: 'danger'}))
            : 'Alerts';
    },
    fireImmediately: true  // Set initial title from current count
});

Reacting to Tab Changes

this.addReaction({
    track: () => this.tabModel.activeTabId,
    run: id => {
        if (id === 'details') {
            this.loadDetailsAsync();
        }
    }
});

Common Pitfalls

Setting activeTabId Directly

// ❌ Don't: Setting activeTabId directly won't trigger proper tab activation
tabModel.activeTabId = 'details';

// βœ… Do: Use setActiveTabId()
tabModel.setActiveTabId('details');

setActiveTabId() handles routing updates, refresh triggers, and other side effects that direct property assignment would bypass. It can also be used as a bind target for UI controls (e.g., SegmentedControl) that need to switch tabs.

Missing Route Definitions

Setting route on a TabContainerModel without defining matching routes in your AppModel's getRoutes() will silently fail - tabs will render but URL navigation won't work. Ensure every routed tab ID has a corresponding route name in the hierarchy:

// ❌ Tab has route but no matching route definition in AppModel.getRoutes()
new TabContainerModel({
    route: 'main',
    tabs: [{id: 'overview', ...}]  // Won't route unless 'main' with child 'overview' is defined
});

// βœ… Route hierarchy in AppModel matches tab IDs
getRoutes() {
    return [{name: 'main', path: '/main', children: [
        {name: 'overview', path: '/overview'}
    ]}];
}

Related Packages

  • /desktop/cmp/tab/ - Desktop TabContainer component with Blueprint tabs
  • /mobile/cmp/tab/ - Mobile TabContainer component with a docked button switcher
  • /core/ - RefreshContextModel, RenderMode, RefreshMode