Nucleus
Tool windows

TabsNew

Declare documents as Chrome-like tabs that reorder, tear off into windows and merge back, with custom strips, previews and saved layouts.

View as Markdown

TabWindows and Tab give an app the Chrome tab model: a tab strip in every window's title bar, windows that appear when a tab is torn off and close when their last tab leaves. Tabs are @ExperimentalNucleusApi (see Tool windows).

Declare tabs

Create a TabWorkspace, compose TabWindows once, and declare every tab at application scope:

Main.kt
fun main() = nucleusApplication {
    val workspace = rememberTabWorkspace()
    TabWindows(workspace, onLastWindowClosed = ::exitApplication)

    for (document in documents) {
        key(document.id) {
            Tab(workspace, id = document.id, title = document.name) { Editor(document) }
            DropClosedTab(workspace, documents, document.id)
        }
    }
}

TabWindows opens one window per group of tabs, with the strip in its title bar and the selected tab as its body. Never declare a Tab inside a window.

When the user closes a tab, the workspace forgets it but your list still declares it. Drop it from the list, or the next composition registers it again:

@Composable
private fun DropClosedTab(workspace: TabWorkspace, documents: MutableList<Document>, id: String) {
    val closed = workspace.tab(id) == null
    LaunchedEffect(closed) { if (closed) documents.removeAll { it.id == id } }
}

Tab and TabWindows parameters

Tab(workspace, id, title, group = null) { … } opens in group on first declaration, else in the window focused last, else in a new window. The selected tab's title is the window title. The body runs with TabScope: workspace, tab, select(), close().

TabWindows parameterDefaultMeaning
workspacerequiredThe TabWorkspace
strip{ TabStrip() }One window's strip, with TabStripScope as receiver
titleBar{ DefaultTabTitleBar(it) }Each window's title bar, handed the strip to place in it
dragGhost{ TabDragGhostCard(it) }The card under the pointer while a tab leaves its strip
nativeContextMenutrueNative context menu for text fields
windowWrapper{ it() }Wraps each window, strip included: WindowBackground, a themed Surface
windowBodyWrapper{ it() }Wraps what is under the strip: a DockLayout, a status bar
onLastWindowClosed{}Called each time the workspace goes from holding tabs to holding none

Both wrappers receive the window's NucleusDecoratedWindowScope and must invoke their lambda. Set the theme around TabWindows, not inside a window: the workspace passes those locals to every window it opens.

MaterialTheme(colorScheme = colors) {
    CompositionLocalProvider(LocalTitleBarStyle provides rememberMaterialTitleBarStyle(colors)) {
        TabWindows(workspace, onLastWindowClosed = ::exitApplication)
        // Tab declarations
    }
}

DefaultTabTitleBar is a BasicTitleBar that gives the strip all the width between the window controls. Replace it to keep a title bar of your own, such as a gradient, fullscreen controls or ControlButtonsDirection.SystemNative:

TabWindows(
    workspace = workspace,
    strip = { MyStrip() },
    titleBar = { strip -> JewelTitleBar(gradientStartColor = accent) { strip() } },
)

rememberTabWorkspace(defaultWindowSize, captureThumbnails) takes the size of new windows (960 × 640 dp by default) and whether to capture thumbnails (false).

Drag tabs

With the stock strip, the user drags a tab along the strip to reorder it, out of the window to open a new one, or onto another window's strip to merge it. Dragging the only tab of a window moves the window itself. A tab pulled out of a maximized window opens at defaultWindowSize.

Modifier.tabDragHandle(workspace, tab) is the grip TabStrip puts on every tab. On native Wayland it reorders inside the strip, then hands off to a platform drag when the pointer leaves: draggedTab is set while dragKind is still null during the local phase. A custom strip in the title bar also applies Modifier.noWindowDrag() to each grip, so the compositor's window move does not swallow the gesture.

For a right-to-left strip, provide LayoutDirection.Rtl around TabStrip. Reorder and drop indices follow it.

Reordering a tab, tearing one off into its own window, then dropping it back on the strip

Customize the stock strip

TabStrip parameterDefaultMeaning
reorderAnimationspring, StiffnessMediumLowHow a tab travels along the strip; null moves it at once
hoverPreviewnullThe card under a hovered tab. TabHoverPreview.Default for the stock card
tabLeading / tabTrailingnullPer-tab slots around the title: a file icon, a modified dot
dropGhostCard{ TabDropGhostCard(it) }The card in the slot a tab from another window would fill
gripCursorTabGripCursor.DefaultThe pointer over a tab and while it is carried. TabGripCursor.None keeps the strip's arrow
trailing{}After the last tab: a new-tab button (a tab dropped on it is appended)
TabWindows(
    workspace = workspace,
    strip = {
        TabStrip(
            hoverPreview = TabHoverPreview.Default,
            tabTrailing = { tab -> if (tab.id in modified) Text("●") },
            trailing = { IconButton(onClick = ::openDocument) { Text("+") } },
        )
    },
)

TabStripScope exposes workspace, group, tabs (in strip order), dropGhost and hoveredTab.

Write a strip from scratch

A strip from another design system gets the stock strip's gestures from rememberTabStripDrag: the carry along the strip, the slide home on release and the hand-over once a tab leaves it.

PartApply to
Modifier.tabStripGeometry(workspace, group)The element spanning the whole strip
Modifier.tabStripGrip(scope, drag, tab, index, cursor)Each tab's slot, the element that stays put
Modifier.tabStripCarry(drag, tab)What the tab draws, which follows the pointer
@Composable
fun TabStripScope.MyStrip() {
    val scope = this
    val drag = rememberTabStripDrag()
    Row(Modifier.tabStripGeometry(workspace, group)) {
        tabs.forEachIndexed { index, tab ->
            key(tab.id) {
                Box(
                    Modifier
                        .zIndex(if (drag.animating == tab.id) 1f else 0f)
                        .tabStripGrip(scope, drag, tab, index, cursor = TabGripCursor.None),
                ) {
                    MyTab(tab, Modifier.tabStripCarry(drag, tab))
                }
            }
        }
    }
}

tabStripGrip combines tabSlot, noWindowDrag and the drag handle. Put it on the slot, not on the carried drawing: a gesture on a node that moves with the pointer reads no movement. TabStripDrag exposes held, animating and offsetPx(tabId). rememberTabStripDrag takes the same reorderAnimation as TabStrip.

For a strip that keeps its own gestures, apply Modifier.tabSlot(group, index) to each tab and Modifier.tabDragHandle(workspace, tab) to its grip instead.

While a tab from another window hovers the strip, dropGhost holds a TabDropGhost(index, width, tab): compose TabDropGhostCard(ghost) at index. Add TabHoverPreviewPopup(preview) once for hover cards. The workspace.tabs probe of the Nucleus Lab wraps Jewel's TabStrip this way: pick Jewel under Strip.

Open the tab windows yourself

TabWindows is built from public parts. An app that needs its own window per group (its own state, title, key handling or close policy) composes them directly and keeps the workspace behavior:

PartRole
BindTabGroupWindow(workspace, group, window)Attaches the window to its group for drops, tear-offs and focus. Call it once inside the window
TabGroupWindowPlacement(group, state)Applies the positions and sizes the workspace asks for (restore, tear-off) to your WindowState
TabDragGhostWindow(workspace, nativeContextMenu, content)The window that follows a dragged tab. Compose it once, next to your windows
for (group in rememberTabGroups(workspace)) {
    key(group.id) {
        val state = rememberWindowState(
            position = group.position?.let { WindowPosition.Absolute(it.x, it.y) }
                ?: WindowPosition.PlatformDefault,
            size = group.size,
        )
        TabGroupWindowPlacement(group, state)
        DecoratedWindow(
            state = state,
            title = workspace.selectedTab(group)?.title.orEmpty(),
            onCloseRequest = { group.ids.forEach(workspace::close) },
        ) {
            BindTabGroupWindow(workspace, group)
            MyWindowContent(workspace, group)
        }
    }
}
TabDragGhostWindow(workspace)

The window body is yours: draw the tab that workspace.selectedTab(group) returns. A strip in such a window gets its TabStripScope from an object that implements workspace and group. rememberTabGroups is defined in Compose tabs with satellites.

Draw previews

Thumbnails. TabEntry.thumbnail is an ImageBitmap?. With captureThumbnails = true the workspace records each window's selected tab; call captureThumbnail(tabId) after a visible change. You can also assign one yourself before the tab is shown. NativeView and TextureView content is missing from captures. TabPreview(tab, modifier, contentScale, placeholder) draws the thumbnail.

Hover cards. TabHoverPreview(delay, offset, content) describes the card. delay defaults to 650 ms. The card fades in, slides from tab to tab while the pointer moves along the strip, and fades out. Coming back to the strip right after leaving it shows the card again without the delay. The stock card is TabHoverPreviewCard(modifier, subtitle = null):

val preview = remember {
    TabHoverPreview { TabHoverPreviewCard(subtitle = { Text(pathOf(tab.id), maxLines = 1) }) }
}
TabStrip(hoverPreview = preview)

The card opens like the window's other popups. The windows TabWindows opens draw it inside the window, clipped by it. To let it hang below the window, as a browser's does, open the tab windows yourself with nativePopupLayers = true. See Open popups as native surfaces.

Drag and drop cards. Draw TabWindows(dragGhost) and TabStrip(dropGhostCard) with the same composable, built on TabGhostCard(tab, modifier), so the tab lands as it travelled. dragGhost runs outside windowWrapper and never on native Wayland.

The hover card fades in, then slides from tab to tab

Drive tabs from code

CallEffect
select(tabId)Make it the visible tab of its group
close(tabId)Remove it, state included; an empty group closes its window
move(tabId, group, index = null)Move it into group at index (null appends) and select it
reorder(tabId, index)Move it within its group
tearOff(tabId, screenRectPx, scaleFactor)Open it in a new window at a screen rect in physical pixels

Read tabs, tab(id), groups, group(id), activeGroup (where new tabs open), groupOf(window), tabsOf(group), selectedTab(group), and the drag in flight with draggedTab, dropPreview, dragGhost, dragKind. A closed tab is gone: declaring it again creates a new tab in the active window.

Keep pinned tabs first

TabWorkspace.constrainIndex narrows where a tab may stand in a group. It receives the tab, the group and the index the tab would take, and returns the index it may take instead. This keeps pinned tabs ahead of the others, as a browser does:

val workspace = rememberTabWorkspace()
workspace.constrainIndex = { tabId, group, index ->
    val pinnedCount = group.ids.count { it in pinned && it != tabId }
    if (tabId in pinned) index.coerceAtMost(pinnedCount) else index.coerceAtLeast(pinnedCount)
}

Every placement goes through it: move, reorder, a tab's first declaration, and the drop preview of a drag in its own strip, another window's or a linked workspace's. The other tabs only make room where the dragged tab can land, so a release never puts it anywhere else. Set it before the first Tab declaration so first placements follow it too. null, the default, allows any index.

Drag tabs between workspaces

An app with several TabWorkspaces, for example one per virtual desktop, can let a tab cross from one to another. Link them and handle the drop:

LaunchedEffect(workspaces) {
    for (workspace in workspaces) {
        workspace.linkedWorkspaces = workspaces - workspace
        workspace.onForeignDrop = { tab, into, target ->
            // Only the app can declare the tab in the other workspace
            moveDocument(tab.id, from = workspace, to = into, group = target.group.id, index = target.index)
        }
    }
}
  • Linked strips are tried after the workspace's own, for pointer drags only. Native Wayland's drag-and-drop path ignores them.
  • The workspace leaves the dropped tab where it was. onForeignDrop closes it there and declares it in into, at the TabDropTarget it received.
  • While the pointer is over a linked strip, dropPreview points at that workspace's group.
  • With onForeignDrop = null (the default), linked strips are no target and the drop tears the tab off.
  • Where strips of several workspaces overlap, the strip under the pointer wins, then the window focused last, across workspaces.

Save and restore the layout

snapshot() returns a TabLayoutSnapshot(groups). Each TabGroupSnapshot holds id, tabIds, selectedId, position and size. restore(snapshot) moves the tabs and places the windows, including tabs declared later. It applies once; call it again after a tab is closed and redeclared. A window torn off after a restore never takes the id of a restored group.

Compose tabs with satellites

Give each tab window its own SatelliteWorkspace, keyed by group id, and let its satellites draw the selected tab. A tab change then only swaps content.

TabWindows(
    workspace = tabs,
    windowWrapper = { content ->
        tabs.groupOf(nucleusWindow.unsafe.taoWindow)?.let { JoinSatelliteWorkspace(panesOf(it.id)) }
        content()
    },
    windowBodyWrapper = { body ->
        val group = tabs.groupOf(nucleusWindow.unsafe.taoWindow)
        if (group == null) body() else DockLayout(panesOf(group.id), Modifier.fillMaxSize()) { body() }
    },
)

for (group in rememberTabGroups(tabs)) {
    key(group.id) {
        val document = tabs.selectedTab(group)?.let { documentOf(it.id) }
        Satellite(panesOf(group.id), id = "inspector-${group.id}", title = "Inspector") {
            Inspector(document)
        }
    }
}

rememberTabGroups mirrors workspace.groups through an effect, since Tab creates groups during the composition that reads the list:

@Composable
fun rememberTabGroups(workspace: TabWorkspace): List<TabWindowGroup> {
    var groups by remember(workspace) { mutableStateOf(workspace.groups.toList()) }
    LaunchedEffect(workspace) { snapshotFlow { workspace.groups.toList() }.collect { groups = it } }
    return groups
}

Open and close those satellites from a LaunchedEffect, never during composition. The workspace.tab-satellites and workspace.reader-dock probes of the Nucleus Lab show both setups.

What's next

  • Satellites: palettes, headers and owners.
  • Docking: the DockLayout a tab window can host.
  • Toolkits: title-bar styles the stock strip picks up.
Was this page helpful?
Edit on GitHub

Last updated on