Border LayoutORG
An application frame in five regions - north, south, west and east around a center - with every divider draggable. It reuses the Resizer: each side is a .resizer wrapping its pane, and inside a border layout its handle becomes a full-length divider you drag or move with the arrow keys. Leave regions out and the same frame is a horizontal split, a vertical split or three columns; nest it for more. North/south or west/east dominant, grips, dashed / dotted / double / gap dividers, custom handles, collapsible and remembered panels - after shadcn's Resizable.
On this page (21)
§Border layout
Five regions on a grid: north and south span the width (the default, data-dominant='ns'), west and east sit between them around the center. Every side is a .resizer wrapping its pane - drag a line, or Tab to it and use the arrow keys (they move the line the way they point; Home / End jump to the limits). The center never drops below 120px.
§West and east dominate
data-dominant='we': west and east run the full height, north and south sit between them above and below the center - the frame of an IDE with full-height sidebars.
§Horizontal split
Just west and a center: two panes side by side, the regions left out take no room. The west pane starts at 50%; a drag writes px.
§Nested splits
A border layout in the center of another, with data-frame='none': a horizontal split whose right side is split vertically. Each divider belongs to its own layout.
§Regions that fit their content
data-fit on a fixed region (no resizer): it is as high as its content, between --border-layout-fit-min and --border-layout-fit-max (half the layout by default), and scrolls past the maximum. Add steps: the south grows until it reaches half the frame, then its list scrolls and the editor keeps the rest. The north keeps at least a fifth of the frame. CSS only - the layout is a size container for the bounds, so it takes its height from outside.
§Several panels on one side
A .border-layout-stack as the region's pane holds several Panels - top to bottom in west / east, side by side in north / south. Drag the line between two panels (or Tab to it and use the arrows) to share the room; minimize one and the others take its room; minimize all and the region folds to vertical tabs, like a single Panel. Maximize fills the layout.
§One panel open at a time
data-exclusive on the stack keeps one panel open, like an accordion: open one (its chevron, or a double-click on its tab) and the open one minimizes. Both start minimized here, so the east side starts as two vertical tabs; minimize the open one and it folds back.
§Side by side in one region
data-direction='row' lays the stack's panels side by side on any side - here on the east, as columns. With data-exclusive one is open and the others are vertical tabs beside it; open a tab and the open column folds to its tab. data-direction='column' stacks them top to bottom in north / south.
A row stack with data-levels is a trail: each level keeps its own width and the region is their sum. Pick a section, then a book - every pick adds a level (push), data-keep='2' folds the earlier ones to bars, and the center gets their room. With data-drill a folded level is a breadcrumb: click its bar (or Tab to it, Enter) and the levels after it go.
§Levels on the east side
On the east side the levels run from the edge toward the center - the deepest next to the center. Three levels are authored open with data-keep='2', so the outermost starts as a bar. Drag the line after a level to change its own width.
§Custom handle
The divider is a .resizer-handle: --border-layout-divider-color / -width / --border-layout-accent retheme it, and plain CSS on its ::before (the line) and ::after (the grip) makes any handle - here a bold primary rail with a round knob.
§Grips
data-grip on the layout draws a handle on every divider: dots (a small dotted card) or bar (a pill); on one region's resizer it overrides the layout - data-grip='none' switches it off there.
§Divider styles
data-divider: solid (the default), dashed, dotted, double, thick, none - invisible but still draggable - and gap, where the regions float as cards in a gutter and the divider lives in the gap. Set it on one region's resizer to style just that divider.
§Collapsible and remembered
data-collapsible: double-click a divider (or focus it and press Enter) to fold its region away - the divider stays to bring it back, and dragging it unfolds. data-save='…' remembers sizes and folded regions across visits (a persisted store in localStorage) - resize, reload the page, it comes back as you left it. The buttons use df$.shadcn.borderLayout.
§An application window
The frame of an app, in a Window: a menubar in the north, a file tree in the west, the editor in the center, an outline in the east and a terminal (a code mockup) in the south - west and east dominate. Every divider drags; View folds and unfolds the panels through df$.shadcn.borderLayout.
§States
Named states via the shared State API, driven per layout through the bound api:
default- every region open; setting it restores the authored sizescollapsed- one or more regions folded:{ regions: ['west', 'south'] }or{ region: 'west' }
The first example carries data-state-demo; bun run screenshots drives it via el.api.setState(name) and captures screenshots/{mode}/border-layout-{state}.png.
Machine contract - verified against border-layout.schema.json by bun run verify:
| State | Type | Values | Default | Description |
|---|---|---|---|---|
collapsed | boolean | true, false | false | One or more regions folded away (the schema folds west); default opens them all. |
§API
Generated from border-layout.ts and the shared State API - the descriptions are their JSDoc, the types are checked by the compiler.
States
type BorderLayoutState = 'default' | 'collapsed' - setState(name, config) takes the config of the state it names.
| State | Description | |||||||||
|---|---|---|---|---|---|---|---|---|---|---|
default | Every region open at its authored size. No config. | |||||||||
collapsed | One or more regions folded away (their dividers stay).
|
Every element
| Member | Description | |||||||||
|---|---|---|---|---|---|---|---|---|---|---|
el.api.setState<S extends BorderLayoutState>(name: S, config?: BorderLayoutStateConfigs[S]): unknown | Enter a state: the DOM work runs (also when it is the current state), the store records it.
Returns | |||||||||
el.api.getState(): { name: BorderLayoutState; config: BorderLayoutStateConfigs[BorderLayoutState]; model?: ElementModel } | The state the element shows now - read back from the DOM, so it includes what the user changed. Returns | |||||||||
el.api.render(state?: { name: BorderLayoutState; config: BorderLayoutStateConfigs[BorderLayoutState]; model?: ElementModel }): string | The element's markup in a state - the authored markup with that state applied; a pure function of the state.
Returns | |||||||||
el.api.settled(): Promise<void> | Wait for the last state's DOM work (async states: a diagram rendering, a chart mounting). Returns | |||||||||
el.store: Store<{ name: BorderLayoutState; config: BorderLayoutStateConfigs[BorderLayoutState] }> | A defuss-store store of the element's state - subscribe to follow every change (also the user's), set it to drive the component. |
Registry
| Member | Description | ||||||||||||
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
df$.shadcn.borderLayoutApi.setState<S extends BorderLayoutState>(el: HTMLElement, name: S, config?: BorderLayoutStateConfigs[S]): unknown | Enter a state: the DOM work runs (also when it is the current state), the store records it.
Returns | ||||||||||||
df$.shadcn.borderLayoutApi.getState(el: HTMLElement): { name: BorderLayoutState; config: BorderLayoutStateConfigs[BorderLayoutState]; model?: ElementModel } | The state the element shows now - read back from the DOM, so it includes what the user changed.
Returns | ||||||||||||
df$.shadcn.borderLayoutApi.render(state: { name: BorderLayoutState; config: BorderLayoutStateConfigs[BorderLayoutState]; model?: ElementModel }): string | The element's markup in a state - the authored markup with that state applied; a pure function of the state.
Returns | ||||||||||||
df$.shadcn.borderLayoutApi.store(el: HTMLElement): Store<{ name: BorderLayoutState; config: BorderLayoutStateConfigs[BorderLayoutState] }> | The element's store (bindComponent made it).
Returns | ||||||||||||
df$.shadcn.borderLayoutApi.commit<S extends BorderLayoutState>(el: HTMLElement, name: S, config?: BorderLayoutStateConfigs[S]): void | Record a state the element reached on its own (no DOM work) - for a component's own handlers.
| ||||||||||||
df$.shadcn.borderLayoutStates: BorderLayoutState[] | The declared states, 'default' first: default, collapsed. |
df$.shadcn.borderLayout
| Member | Description | ||||||||||||
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
collapse(target: string | HTMLElement, side: BorderLayoutSide): void | Folds a region away (its divider stays).
| ||||||||||||
expand(target: string | HTMLElement, side: BorderLayoutSide): void | Brings a folded region back.
| ||||||||||||
toggle(target: string | HTMLElement, side: BorderLayoutSide): boolean | Folds or unfolds a region.
Returns | ||||||||||||
resize(target: string | HTMLElement, side: BorderLayoutSide, px: number): void | Sets a region's size (clamped by the resizer's limits).
| ||||||||||||
push(stack: string | HTMLElement, panel: HTMLElement | string): HTMLElement | null | Adds a level to a stack (deep navigation): the panel goes after the others, opens, and data-keep folds the earlier levels to bars.
Returns | ||||||||||||
pop(stack: string | HTMLElement, panel: HTMLElement | string | number): HTMLElement | null | Goes back to a level: every level after it goes, and it opens.
Returns | ||||||||||||
levels(stack: string | HTMLElement): BorderLayoutStackChangeDetail | A stack's levels, outermost first.
Returns | ||||||||||||
sizes(target: string | HTMLElement): Partial<Record<BorderLayoutSide, number>> | The current sizes: { west: 240, east: 0 (collapsed), ... }.
Returns |
Events
| Event | Description | |||||||||
|---|---|---|---|---|---|---|---|---|---|---|
border-layout-collapse | Fires when a region folds away or comes back - which region, and whether it is collapsed now.
| |||||||||
border-layout-stack-change | Fires when a stack's panels change - one added or removed, opened, minimized or closed - with its levels in order.
|
Types
| Type | Description | |||||||||
|---|---|---|---|---|---|---|---|---|---|---|
BorderLayoutCollapseDetail | What border-layout-collapse carries.
| |||||||||
BorderLayoutSide | A region that folds and resizes - the center takes what is left. = | |||||||||
BorderLayoutStackChangeDetail | What border-layout-stack-change carries: a stack's levels, outermost first.
|
§CSS view file
/* -- Border Layout component -------------------------------------- An application frame in five regions - north, south, west, east around a center - on a CSS grid. Every side region that should resize is a .resizer wrapping its pane: inside a border layout the resizer's handle becomes a full-length divider (line, optional grip), dragged or moved with the arrow keys. Regions left out collapse, so the same frame is a horizontal split, a vertical split, three columns... */@layer components { .border-layout { /* the divider, themable per layout or per region */ --_line-width: var(--border-layout-divider-width, 1px); --_line-style: solid; --_line-color: var(--border-layout-divider-color, var(--border)); --_accent: var(--border-layout-accent, var(--ring)); --_hit: 0.75rem; --_gap: 0px; display: grid; grid-template-columns: auto minmax(0, 1fr) auto; grid-template-rows: auto minmax(0, 1fr) auto; /* north and south dominate: they span the full width */ grid-template-areas: "north north north" "west center east" "south south south"; gap: var(--_gap); min-width: 0; min-height: 0; overflow: hidden; border: 1px solid var(--border); border-radius: var(--radius-lg); background: var(--card); color: var(--card-foreground); /* west and east dominate: they span the full height */ &[data-dominant="we"] { grid-template-areas: "west north east" "west center east" "west south east"; } /* no frame of its own - fills a window or a page */ &[data-frame="none"] { border: 0; border-radius: 0; background: transparent; } } .border-layout > .border-layout-north { grid-area: north; } .border-layout > .border-layout-south { grid-area: south; } .border-layout > .border-layout-west { grid-area: west; } .border-layout > .border-layout-east { grid-area: east; } .border-layout > .border-layout-center { grid-area: center; min-width: 0; min-height: 0; overflow: auto; } /* -- Regions ------------------------------------------------------ */ /* a resizable region: the resizer wrapper fills its grid cell, its pane stretches across the other axis and carries the size on its own */ .border-layout > .resizer { display: flex; width: auto; min-width: 0; min-height: 0; } .border-layout > :is(.border-layout-north, .border-layout-south).resizer { flex-direction: column; } .border-layout > .resizer > :not(.resizer-handle) { flex: none; box-sizing: border-box; min-width: 0; min-height: 0; overflow: auto; } /* the pane of a collapsed region is gone; its divider stays to bring it back */ .border-layout > .resizer[data-collapsed] > :not(.resizer-handle) { display: none; } /* a region that does not resize still gets the divider line */ .border-layout > .border-layout-north:not(.resizer) { border-block-end: var(--_line-width) var(--_line-style) var(--_line-color); } .border-layout > .border-layout-south:not(.resizer) { border-block-start: var(--_line-width) var(--_line-style) var(--_line-color); } .border-layout > .border-layout-west:not(.resizer) { border-inline-end: var(--_line-width) var(--_line-style) var(--_line-color); } .border-layout > .border-layout-east:not(.resizer) { border-inline-start: var(--_line-width) var(--_line-style) var(--_line-color); } /* -- Fit: a fixed side region sized by its content ------------------- data-fit on a fixed region (no resizer): its size is its content's - a tree that grows, a list of states - between --border-layout-fit-min and --border-layout-fit-max (half the layout by default); past the maximum its content scrolls. The side rows and columns are `auto` tracks, which take an item's clamped size: CSS only. The bounds are container units of the layout, so a layout holding a fit region is a size container - it takes its height from outside (a height, a grid cell), never from its content. A panel in it that is minimized or maximized leaves the bounds. */ .border-layout:has(> [data-fit]) { container-type: size; } .border-layout > :is(.border-layout-north, .border-layout-south)[data-fit]:not( [data-minimized], [data-maximized], [data-panel-minimized] ) { min-block-size: var(--border-layout-fit-min, 0px); max-block-size: var(--border-layout-fit-max, 50cqh); overflow: auto; } .border-layout > :is(.border-layout-west, .border-layout-east)[data-fit]:not( [data-minimized], [data-maximized], [data-panel-minimized] ) { min-inline-size: var(--border-layout-fit-min, 0px); max-inline-size: var(--border-layout-fit-max, 50cqw); overflow: auto; } /* padding for panes that hold text (optional) */ .border-layout-pane { padding: 0.75rem; } /* -- Dividers: the resizer handle, redrawn --------------------------- */ .border-layout > .resizer > .resizer-handle { z-index: 5; width: auto; height: auto; border: 0; border-radius: 0; background: transparent; box-shadow: none; opacity: 1; color: var(--muted-foreground); /* the line */ &::before { content: ""; position: absolute; transition: border-color 120ms; } /* the grip - hidden unless data-grip asks for one */ &::after { content: none; inset: auto; } &:hover, &:focus-visible { background: transparent; outline: none; } &:is(:hover, :focus-visible)::before { border-color: var(--_accent); } &:focus-visible::after { outline: 2px solid var(--_accent); outline-offset: 1px; } /* vertical dividers: west's east edge, east's west edge */ &:is([data-handle="e"], [data-handle="w"]) { top: 0; bottom: 0; width: var(--_hit); cursor: col-resize; &::before { inset-block: 0; left: 50%; border-inline-start: var(--_line-width) var(--_line-style) var(--_line-color); translate: -50% 0; } } &[data-handle="e"] { right: 0; left: auto; translate: calc(50% + var(--_gap) / 2) 0; } &[data-handle="w"] { left: 0; right: auto; translate: calc(-50% - var(--_gap) / 2) 0; } /* horizontal dividers: north's south edge, south's north edge */ &:is([data-handle="n"], [data-handle="s"]) { left: 0; right: 0; height: var(--_hit); cursor: row-resize; &::before { inset-inline: 0; top: 50%; border-block-start: var(--_line-width) var(--_line-style) var(--_line-color); translate: 0 -50%; } } &[data-handle="s"] { bottom: 0; top: auto; translate: 0 calc(50% + var(--_gap) / 2); } &[data-handle="n"] { top: 0; bottom: auto; translate: 0 calc(-50% - var(--_gap) / 2); } } /* dragging: the divider lights up; the resizer's own box outline stays off */ .border-layout > .resizer[data-resizing] { outline: none; & > .resizer-handle { background: transparent; } & > .resizer-handle::before { border-color: var(--_accent); } } /* -- Grips: data-grip on the layout (every divider) or on one region -- */ :is(.border-layout[data-grip] > .resizer, .border-layout > .resizer[data-grip]) > .resizer-handle::after { content: ""; position: absolute; top: 50%; left: 50%; translate: -50% -50%; box-sizing: border-box; border-radius: var(--radius-sm); } /* dots: a small card with a dotted grip */ :is(.border-layout[data-grip="dots"] > .resizer, .border-layout > .resizer[data-grip="dots"]) > .resizer-handle::after { width: 0.75rem; height: 1.25rem; border: 1px solid var(--_line-color); background: radial-gradient(circle, currentColor 0.75px, transparent 1.25px) center / 4px 4px, var(--background); } /* bar: a pill across the line */ :is(.border-layout[data-grip="bar"] > .resizer, .border-layout > .resizer[data-grip="bar"]) > .resizer-handle::after { width: 0.25rem; height: 2rem; border-radius: 999px; background: color-mix(in oklch, var(--foreground) 35%, var(--_line-color)); } /* data-grip="none" - on the layout (regions without their own grip) or one region - switches it off; more specific than the rules above */ :is(.border-layout[data-grip="none"] > .resizer:not([data-grip]), .border-layout > .resizer[data-grip="none"]) > .resizer-handle::after { content: none; } /* horizontal dividers turn the grip sideways */ .border-layout .resizer > .resizer-handle:is([data-handle="n"], [data-handle="s"])::after { rotate: 90deg; } .border-layout .resizer > .resizer-handle:is(:hover, :focus-visible)::after { border-color: var(--_accent); } /* -- Divider styles (data-divider on the layout or one region) ----------- */ :is(.border-layout, .border-layout > .resizer, .border-layout > [class*="border-layout-"]) { &[data-divider="dashed"] { --_line-style: dashed; } &[data-divider="dotted"] { --_line-style: dotted; --_line-width: var(--border-layout-divider-width, 2px); } &[data-divider="double"] { --_line-style: double; --_line-width: var(--border-layout-divider-width, 4px); } &[data-divider="thick"] { --_line-width: var(--border-layout-divider-width, 4px); --_line-color: var(--border-layout-divider-color, var(--muted)); } &[data-divider="none"] { --_line-width: 0px; } } /* gap: the regions float as cards in a gutter, the divider lives in the gutter */ .border-layout[data-divider="gap"] { --_gap: 0.5rem; --_line-width: 0px; padding: var(--_gap); background: var(--muted); & > :is( .border-layout-north, .border-layout-south, .border-layout-west, .border-layout-east, .border-layout-center ):not(.resizer), & > .resizer > :not(.resizer-handle) { border: 1px solid var(--border); border-radius: var(--radius-md); background: var(--card); } } /* -- Stacks: several Panels on one side ----------------------------- A region's pane may be a .border-layout-stack of Panels: top to bottom in west / east, side by side in north / south. The panels share the region by weight (--border-layout-share, a flex-grow the runtime writes as px when a divider moves); a minimized one shrinks to its title bar and the others take its room. When every panel is minimized the region folds like a single panel: north / south to the bars, west / east to vertical tabs. data-direction="row" | "column" lays them side by side or top to bottom on any side; in a row on west / east a minimized panel is a vertical tab. */ .border-layout-stack { display: flex; flex-direction: column; min-width: 0; min-height: 0; overflow: hidden; & > .panel { flex: var(--border-layout-share, 1) 1 0px; min-width: 0; min-height: 0; border: 0; border-radius: 0; } & > .panel[data-minimized] { flex: none; } } .border-layout > :is(.border-layout-north, .border-layout-south) > .border-layout-stack:not([data-direction="column"]), .border-layout > .border-layout-stack:is(.border-layout-north, .border-layout-south):not([data-direction="column"]), .border-layout-stack[data-direction="row"] { flex-direction: row; } /* north / south: a minimized panel keeps its bar at the start of its column */ :is(.border-layout-north, .border-layout-south) > .border-layout-stack:not([data-direction="column"]) > .panel[data-minimized], .border-layout-stack:is(.border-layout-north, .border-layout-south):not([data-direction="column"]) > .panel[data-minimized] { align-self: flex-start; } /* west / east in a row (and every west / east stack folded): a minimized panel turns into a vertical tab - the Panel's own west / east tab, for panels a stack holds */ :is(.border-layout-west, .border-layout-east) > .border-layout-stack[data-direction="row"] > .panel[data-minimized], .border-layout-stack[data-direction="row"]:is(.border-layout-west, .border-layout-east) > .panel[data-minimized], .border-layout > :is(.border-layout-west, .border-layout-east)[data-panel-minimized] > .border-layout-stack > .panel, .border-layout > .border-layout-stack:is(.border-layout-west, .border-layout-east)[data-panel-minimized] > .panel { inline-size: auto !important; min-inline-size: 0; container-type: normal; & > .panel-header { flex: 1; writing-mode: vertical-rl; padding-block: 0.25rem; padding-inline: 0.375rem 0.75rem; border-block-end: 0; } & .panel-tools { order: -1; margin-inline: 0 0.25rem; } & .panel-maximize { display: none; } } /* west: the tab reads from the bottom up and starts at the top - the chevron, the title, the tools (as the Panel's own west tab) */ .border-layout-west > .border-layout-stack[data-direction="row"] > .panel[data-minimized] > .panel-header, .border-layout-stack[data-direction="row"].border-layout-west > .panel[data-minimized] > .panel-header, .border-layout > .border-layout-west[data-panel-minimized] > .border-layout-stack > .panel > .panel-header, .border-layout > .border-layout-stack.border-layout-west[data-panel-minimized] > .panel > .panel-header { rotate: 180deg; justify-content: flex-end; & .panel-tools { display: contents; } & .panel-icon, & .panel-title { order: 1; flex: none; } & .panel-minimize { order: 2; rotate: 90deg; } } /* deep navigation (data-levels on a row stack): each open level keeps its own width (--panel-size), a folded one is its bar, and the region is their sum - what a level gives up goes to the center. On the east side the levels run from the edge toward the center. A folded level in a drill stack is a breadcrumb: it takes the pointer. */ .border-layout-stack[data-levels] > .panel:not([data-minimized]) { flex: none; inline-size: var(--panel-size, 16rem); } .border-layout-east > .border-layout-stack[data-levels], .border-layout-stack[data-levels].border-layout-east { flex-direction: row-reverse; } .border-layout-stack[data-drill] > .panel[data-minimized] > .panel-header { cursor: pointer; &:hover { background: var(--accent); color: var(--accent-foreground); } &:focus-visible { outline: 2px solid var(--ring); outline-offset: -2px; } } /* the divider between two panels: a line with a wider hit area */ .border-layout-stack-divider { position: relative; z-index: 4; flex: none; block-size: var(--_line-width); margin-block: calc((var(--_hit) - var(--_line-width)) / -2); padding-block: calc((var(--_hit) - var(--_line-width)) / 2); background: var(--_line-color) content-box; cursor: row-resize; touch-action: none; transition: background-color 120ms; &:is(:hover, :focus-visible, [data-resizing]) { background-color: var(--_accent); outline: none; } &:focus-visible { box-shadow: inset 0 0 0 2px var(--_accent); } /* next to a minimized panel there is nothing to share */ &[aria-disabled="true"] { cursor: default; background-color: var(--_line-color); } } :is(.border-layout-north, .border-layout-south) > .border-layout-stack:not([data-direction="column"]) > .border-layout-stack-divider, .border-layout-stack:is(.border-layout-north, .border-layout-south):not([data-direction="column"]) > .border-layout-stack-divider, .border-layout-stack[data-direction="row"] > .border-layout-stack-divider { block-size: auto; inline-size: var(--_line-width); margin-block: 0; padding-block: 0; margin-inline: calc((var(--_hit) - var(--_line-width)) / -2); padding-inline: calc((var(--_hit) - var(--_line-width)) / 2); cursor: col-resize; } /* every panel minimized: the region folds with them */ .border-layout > .resizer[data-panel-minimized] > .border-layout-stack { overflow: hidden; } .border-layout > :is(.border-layout-north, .border-layout-south)[data-panel-minimized] > .border-layout-stack, .border-layout > .border-layout-stack:is(.border-layout-north, .border-layout-south)[data-panel-minimized] { block-size: auto !important; } .border-layout > :is(.border-layout-west, .border-layout-east)[data-panel-minimized] > .border-layout-stack, .border-layout > .border-layout-stack:is(.border-layout-west, .border-layout-east)[data-panel-minimized] { inline-size: auto !important; min-inline-size: 0; & > .border-layout-stack-divider { display: none; } /* the tabs share the height - side by side in a row */ &:not([data-direction="row"]) > .panel[data-minimized] { flex: 1 1 0px; } &:not([data-direction="row"]) > .panel ~ .panel { border-block-start: var(--_line-width) var(--_line-style) var(--_line-color); } &[data-direction="row"] > .panel ~ .panel { border-inline-start: var(--_line-width) var(--_line-style) var(--_line-color); } } /* every panel closed: the region leaves with them */ .border-layout > [data-stack-closed] { display: none; } /* -- Accessibility -------------------------------------------- */ @media (prefers-reduced-motion: reduce) { .border-layout > .resizer > .resizer-handle::before, .border-layout-stack-divider { transition: none; } } @media (prefers-contrast: more) { .border-layout { --_line-color: var(--foreground); } } @media (forced-colors: active) { .border-layout { border: 1px solid CanvasText; --_line-color: CanvasText; --_accent: Highlight; } .border-layout > .resizer > .resizer-handle::before { forced-color-adjust: none; } .border-layout-stack-divider { forced-color-adjust: none; background-color: CanvasText; &:is(:hover, :focus-visible, [data-resizing]) { background-color: Highlight; } } }}§JS view file
// -- Border Layout ----------------------------------------------// North, south, west and east around a center, on a CSS grid. The resizing// is the Resizer's: every resizable region is a .resizer wrapping its pane,// with one handle on its inner edge. This module adds the layout on top:// sensible resizer defaults per region, the center never squeezed below its// minimum, collapsible regions (double-click or Enter on the divider),// sizes remembered across visits (data-save), the window-splitter values// on each divider - and the named-state API (AGENTS.md "State API").// Shared preamble (AGENTS.md "State API"); the implementation lives in core.js —// build.ts rewrites this import into a df$.shadcn.shared binding in dist/.import { defussGlobals, defussQuery, componentState, bindComponent, persisted } from '../../../shared/state-api.js';const df$ = defussGlobals();const dfDollar = defussQuery();// VERIFIED: (verify's component types ratchet - tsc -p tsconfig.components.json) every type// this file's API docs state - arguments, return values, event details - holds// against its code: a wrong one is a new type error and fails the build./** A region that folds and resizes - the center takes what is left. */type BorderLayoutSide = 'north' | 'south' | 'west' | 'east';/** What border-layout-stack-change carries: a stack's levels, outermost first. */interface BorderLayoutStackChangeDetail { /** the stack's panels, in order (the outermost level first) */ panels: HTMLElement[]; /** the open ones (not minimized, not closed), in the same order */ open: HTMLElement[];}/** What border-layout-collapse carries. */interface BorderLayoutCollapseDetail { /** the region that folded or came back */ region: BorderLayoutSide; /** whether it is collapsed now */ collapsed: boolean;}/** default = every region open at its authored size; collapsed = one or * more regions folded away (their divider stays). */const borderLayoutStates = ['default', 'collapsed'];/** setState() configs per state. */export interface BorderLayoutStateConfigs { /** Every region open at its authored size. */ default: {}; /** One or more regions folded away (their dividers stay). */ collapsed: { /** the regions to fold */ regions?: BorderLayoutSide[]; /** one region to fold (when regions is not given) */ region?: BorderLayoutSide; };}const SIDES = { north: { handle: 's', axis: 'h', size: 'height' }, south: { handle: 'n', axis: 'h', size: 'height' }, west: { handle: 'e', axis: 'w', size: 'width' }, east: { handle: 'w', axis: 'w', size: 'width' },};const REGIONS = Object.keys(SIDES);const num = (v, fallback) => { const n = parseFloat(v); return Number.isFinite(n) ? n : fallback;};const resolve = (t) => (typeof t === 'string' ? (dfDollar('#' + CSS.escape(t)).get(0) ?? dfDollar(t).get(0)) : t);/** The region element (resizer wrapper or plain pane) for a side. */const regionOf = (layout, side) => dfDollar(layout).find(`:scope > .border-layout-${side}`).get(0);/** The pane that carries the size: the resizer's wrapped element. */const paneOf = (region) => region.classList.contains('resizer') ? Array.from(region.children as HTMLCollectionOf<HTMLElement>).find((c) => !c.classList.contains('resizer-handle')) : region;const sizeOf = (region, side) => { if (region.hasAttribute('data-collapsed')) return 0; const box = region.getBoundingClientRect(); return Math.round(SIDES[side].axis === 'w' ? box.width : box.height);};/** Sets a region's size through the resizer (one axis, clamped) - or directly * on the pane before the resizer has initialized. */function setSize(region, side, px) { const { size } = SIDES[side]; const pane = paneOf(region); if (!pane) return; const value = String(Math.round(px)); if (region.hasAttribute('data-init') && region.api) region.dataset[size] = value; // the resizer applies it else pane.style[size] = `${value}px`;}/** * The center keeps at least data-center-min px (default 120): each side's * maximum is what the frame has left after the opposite side and the * center. Recomputed before every drag / key and whenever the frame * resizes; a side already too big is brought back in. */function clamp(layout) { const centerMin = num(layout.dataset.centerMin, 120); const style = getComputedStyle(layout); const gapW = num(style.columnGap, 0) * 2; const gapH = num(style.rowGap, 0) * 2; const pad = (a, b) => num(style[a], 0) + num(style[b], 0); const innerW = layout.clientWidth - pad('paddingLeft', 'paddingRight') - gapW; const innerH = layout.clientHeight - pad('paddingTop', 'paddingBottom') - gapH; const OPPOSITE = { north: 'south', south: 'north', west: 'east', east: 'west' }; for (const side of REGIONS) { const region = regionOf(layout, side); if (!region?.classList.contains('resizer')) continue; const other = regionOf(layout, OPPOSITE[side]); const taken = other ? sizeOf(other, OPPOSITE[side]) : 0; const room = (SIDES[side].axis === 'w' ? innerW : innerH) - taken - centerMin; const authoredMax = num(region.dataset.maxAuthored, Infinity); const max = Math.max(num(region.dataset.min, 48), Math.min(room, authoredMax)); region.dataset[SIDES[side].axis === 'w' ? 'maxW' : 'maxH'] = String(Math.round(max)); if (!region.hasAttribute('data-collapsed') && sizeOf(region, side) > max + 1) setSize(region, side, max); }}/** The divider speaks the window-splitter pattern: its value is the region size. */function aria(layout) { for (const side of REGIONS) { const region = regionOf(layout, side); const handle = region ? dfDollar(region).children('.resizer-handle').get(0) : null; if (!handle) continue; const pane = paneOf(region); if (pane && !pane.id) pane.id = `${layout.id || 'border-layout'}-${side}-${Math.random().toString(36).slice(2, 7)}`; if (pane) handle.setAttribute('aria-controls', pane.id); const name = region.getAttribute('aria-label') || pane?.getAttribute('aria-label') || side; handle.setAttribute('aria-label', `Resize ${name}`); handle.setAttribute('aria-valuenow', String(sizeOf(region, side))); handle.setAttribute( 'aria-valuemin', String( region.hasAttribute('data-collapsible') || layout.hasAttribute('data-collapsible') ? 0 : num(region.dataset.min, 48), ), ); handle.setAttribute('aria-valuemax', String(num(region.dataset[SIDES[side].axis === 'w' ? 'maxW' : 'maxH'], 2000))); }}const collapsible = (layout, region) => region.hasAttribute('data-collapsible') || layout.hasAttribute('data-collapsible');/** Folds a region away (or back); its divider stays in place to bring it back. */function collapse(layout, side, collapsed) { const region = regionOf(layout, side); if (!region) return; const was = region.hasAttribute('data-collapsed'); if (was === collapsed) return; region.toggleAttribute('data-collapsed', collapsed); aria(layout); save(layout); // Fires when a region folds away or comes back - which region, and whether it is collapsed now. layout.dispatchEvent( new CustomEvent<BorderLayoutCollapseDetail>('border-layout-collapse', { bubbles: true, detail: { region: side, collapsed }, }), ); syncState(layout);}/** The named state follows the regions: any collapsed → 'collapsed'. */function syncState(layout) { const folded = REGIONS.filter((s) => regionOf(layout, s)?.hasAttribute('data-collapsed')); const name = folded.length ? 'collapsed' : 'default'; // the store records it (once bound - init calls this before binding) if (layout.store) borderLayoutApi.commit(layout, name, folded.length ? { regions: folded } : {}); else layout.dataset.stateName = name;}// -- Stacks: several Panels on one side --------------------------------------------// A region's pane may be a .border-layout-stack of Panels (top to bottom in west / east, side by side in north /// south). The runtime puts a divider between every two panels - a window splitter that moves the room between its// two neighbours (drag, arrows) - and follows the panels' states: a minimized panel keeps its title bar and leaves// its room to the others, all minimized fold the region (data-panel-minimized, as a single Panel folds its region),// all closed take it away (data-stack-closed). The Panel owns its own states; the stack only reads them, so a panel// in a stack is a plain Panel (no data-region: its bar stays horizontal until the whole region folds).// data-direction="row" | "column" on the stack lays the panels side by side or top to bottom on any side (a// minimized panel in a row on west / east is a vertical tab); data-exclusive keeps one panel open, like <details// name>: opening one minimizes the others - through the Panel's own State API, the only writer of its states.//// Deep navigation: a row stack with data-levels is a trail of levels (Sections, then Items, then Details). Each open// level keeps its own width (--panel-size), a minimized one is a vertical bar, and the region is their sum - the// room a level gives up goes to the center; on the east side the levels run from the edge toward the center.// data-keep="n" keeps the n levels opened last (data-exclusive is keep 1); data-drill makes a folded level a// breadcrumb: opening it (a click on its bar, Enter) drops the levels after it. push() adds a level, pop() goes back// to one; border-layout-stack-change reports the levels after every change.// VERIFIED: (border-layout.e2e "deep navigation") a stack inside a plain region div is never found - a fixed region// is its own pane, so a trail is `class="border-layout-stack border-layout-west"`; and the event carries elements, not// ids: stamping ids on authored panels would change their markup under the render() contract./** The stack a region holds (its pane, or the region itself when fixed), or null. */const stackOf = (region) => { const pane = region && paneOf(region); return pane?.classList.contains('border-layout-stack') ? pane : null;};const panelsOf = (stack): HTMLElement[] => Array.from(stack.children as HTMLCollectionOf<HTMLElement>).filter((c) => c.classList.contains('panel'));/** side by side: data-direction="row", else (no data-direction="column") on the north / south side */const isRow = (stack, side) => stack.dataset.direction === 'row' || (stack.dataset.direction !== 'column' && (side === 'north' || side === 'south'));/** a panel's extent along the stack (px) */const extent = (panel, row: boolean) => { const box = panel.getBoundingClientRect(); return row ? box.width : box.height;};/** the least room a panel keeps: its own data-min, else its title bar and a little of its body */const minOf = (panel) => { const bar = dfDollar(panel).children('.panel-header').get(0)?.getBoundingClientRect().height ?? 40; return num(panel.dataset.min, Math.round(bar + 32));};const open = (panel) => !panel.hidden && !panel.hasAttribute('data-minimized');const titleOf = (panel) => dfDollar(panel).find(':scope > .panel-header .panel-title').text().trim() || panel.getAttribute('aria-label') || '';/** how many panels stay open: data-exclusive is one, data-keep="n" n, else every one (0) */const keepOf = (stack) => stack.hasAttribute('data-exclusive') ? 1 : Math.max(0, Math.floor(num(stack.dataset.keep, 0)));/** data-keep / data-exclusive: the n panels opened last stay open (of several authored open: the last n), the others * minimize. The order is kept on the stack (_order, the open panels oldest first). */function keepOpen(stack, again: () => void) { const n = keepOf(stack); if (!n) return; const opened = panelsOf(stack).filter(open); const order = (stack._order ?? []).filter((p) => opened.includes(p)); for (const p of opened) if (!order.includes(p)) order.push(p); stack._order = order; const keep = new Set(order.slice(-n)); for (const p of opened) { if (keep.has(p)) continue; // a panel whose script has not run yet (a module loaded after this one) is asked again a task later - a while if (p.api) p.api.setState('minimized'); else if ((stack._waits = (stack._waits ?? 0) + 1) < 50) setTimeout(again); }}/** a stack of levels (data-levels): each open level keeps its own width, the divider after a level resizes it */const levelsOf = (stack) => stack.hasAttribute('data-levels');/** data-drill: a level that opened again (not a new one) drops the levels after it */function drill(stack, panels) { const was = stack._wasOpen; stack._wasOpen = new Set(panels.filter(open)); if (!was || !stack.hasAttribute('data-drill')) return; const reopened = panels.find((p) => open(p) && !was.has(p) && stack._seen?.has(p)); stack._seen = new Set(panels); if (reopened) dropAfter(stack, reopened);}/** removes every level after the given one (with the dividers before them) */function dropAfter(stack, panel) { const panels = panelsOf(stack); for (const p of panels.slice(panels.indexOf(panel) + 1)) { const d = p.previousElementSibling; if (d?.classList.contains('border-layout-stack-divider')) d.remove(); p.remove(); }}/** border-layout-stack-change, when the levels or their open states changed */function report(stack, panels) { const detail: BorderLayoutStackChangeDetail = { panels, open: panels.filter(open) }; const was = stack._reported; stack._reported = detail; const same = (a: HTMLElement[], b: HTMLElement[]) => a.length === b.length && a.every((p, i) => p === b[i]); if (!was || (same(was.panels, detail.panels) && same(was.open, detail.open))) return; // Fires when a stack's panels change - one added or removed, opened, minimized or closed - with its levels in order. stack.dispatchEvent( new CustomEvent<BorderLayoutStackChangeDetail>('border-layout-stack-change', { bubbles: true, detail }), );}/** dividers between the panels, shown where two visible panels meet; the region follows the panels' states */function syncStack(layout, side, region, stack) { keepOpen(stack, () => syncStack(layout, side, region, stack)); drill(stack, panelsOf(stack)); const row = isRow(stack, side); const panels = panelsOf(stack); if (!stack._seen) stack._seen = new Set(panels); for (const p of panels) stack._seen.add(p); // a divider between every two adjacent panels (authored markup has none) for (const panel of panels.slice(1)) { const prev = panel.previousElementSibling; if (prev?.classList.contains('border-layout-stack-divider')) continue; // runtime chrome (data-ce-chrome): the HTML Preview Editor never writes it into a source dfDollar(panel).before( dfDollar( `<div class="border-layout-stack-divider" role="separator" aria-orientation="${row ? 'vertical' : 'horizontal'}" data-ce-chrome></div>`, ), ); } // which divider joins which two visible panels (a closed panel between them is skipped) let last = null, pending = null; for (const child of Array.from(stack.children as HTMLCollectionOf<HTMLElement>)) { if (child.classList.contains('border-layout-stack-divider')) { child._prev = child._next = null; if (last && !pending) pending = child; else if (!child.hidden) child.hidden = true; } else if (child.classList.contains('panel') && !child.hidden) { if (pending) { if (pending.hidden) pending.hidden = false; pending._prev = last; pending._next = child; pending = null; } last = child; } } if (pending && !pending.hidden) pending.hidden = true; // a stray divider (its panel removed) goes with it for (const d of dfDollar(stack).children('.border-layout-stack-divider').toArray()) if (!d.nextElementSibling?.classList.contains('panel')) d.remove(); const levels = levelsOf(stack); for (const d of dfDollar(stack).children('.border-layout-stack-divider').toArray()) { // a level's divider resizes that level alone: it needs only the level open const live = !d.hidden && open(d._prev) && (levels || open(d._next)); d.setAttribute('aria-disabled', String(!live)); d.tabIndex = live ? 0 : -1; if (!d._prev) continue; if (!d._prev.id) d._prev.id = `${stack.id || layout.id || 'stack'}-${Math.random().toString(36).slice(2, 7)}`; d.setAttribute('aria-controls', d._prev.id); d.setAttribute('aria-label', `Resize ${titleOf(d._prev) || 'panel'}`); if (live && levels) { d.setAttribute('aria-valuenow', String(Math.round(extent(d._prev, row)))); d.setAttribute('aria-valuemin', String(minOf(d._prev))); d.setAttribute('aria-valuemax', String(maxLevel(d._prev))); } else if (live) { const both = extent(d._prev, row) + extent(d._next, row); d.setAttribute('aria-valuenow', String(Math.round(extent(d._prev, row)))); d.setAttribute('aria-valuemin', String(minOf(d._prev))); d.setAttribute('aria-valuemax', String(Math.round(both - minOf(d._next)))); } } if (stack.hasAttribute('data-drill')) for (const p of panels) { const header = dfDollar(p).children('.panel-header').get(0) as HTMLElement | undefined; if (!header) continue; const crumb = p.hasAttribute('data-minimized'); if (crumb) { header.tabIndex = 0; header.setAttribute('role', 'button'); header.setAttribute('aria-label', `Back to ${titleOf(p) || 'this level'}`); } else if (header.getAttribute('role') === 'button') { header.removeAttribute('tabindex'); header.removeAttribute('role'); header.removeAttribute('aria-label'); } } const shown = panels.filter((p) => !p.hidden); const folded = shown.length > 0 && shown.every((p) => p.hasAttribute('data-minimized')); region.toggleAttribute('data-panel-minimized', folded); region.toggleAttribute('data-stack-closed', panels.length > 0 && !shown.length); const handle = region.classList.contains('resizer') ? dfDollar(region).children('.resizer-handle').get(0) : null; if (handle) handle.inert = folded || !shown.length; report(stack, panels);}/** the widest a level may get: its data-max, else 640 px */const maxLevel = (panel) => num(panel.dataset.max, 640);/** moves a divider by delta px: the room passes between its two panels; every open panel keeps its px as its share * (--border-layout-share, a flex-grow weight - a custom property, so a minimized panel's flex: none still wins) */function moveDivider(layout, side, divider, delta) { const a = divider._prev, b = divider._next; const stack = divider.parentElement; // a level: the divider after it sets its own width (--panel-size); on the east side the levels run right to left if (a && levelsOf(stack)) { if (!open(a)) return; const px = extent(a, true) + (side === 'east' ? -delta : delta); a.style.setProperty('--panel-size', `${Math.round(Math.min(Math.max(px, minOf(a)), maxLevel(a)))}px`); return; } if (!a || !b || !open(a) || !open(b)) return; const sizes = new Map( panelsOf(stack) .filter(open) .map((p): [HTMLElement, number] => [p, extent(p, isRow(stack, side))]), ); const both = sizes.get(a) + sizes.get(b); const next = Math.min(Math.max(sizes.get(a) + delta, minOf(a)), both - minOf(b)); sizes.set(a, next); sizes.set(b, both - next); for (const [p, px] of sizes) p.style.setProperty('--border-layout-share', String(Math.round(px)));}function initStacks(layout) { for (const side of REGIONS) { const region = regionOf(layout, side); const stack = stackOf(region); if (!stack || stack._stackInit) continue; stack._stackInit = true; const sync = () => syncStack(layout, side, region, stack); sync(); // the panels' states (minimized, closed) and panels added later re-arrange the dividers new MutationObserver((records) => { // a panel's own attributes only - the dividers' hidden flags are this module's writes (reacting to them looped) const panel = (r: MutationRecord) => (r.target as Element).parentElement === stack && (r.target as Element).classList.contains('panel'); if (records.some((r) => (r.type === 'childList' && r.target === stack) || (r.type === 'attributes' && panel(r)))) sync(); }).observe(stack, { childList: true, subtree: true, attributes: true, attributeFilter: ['data-minimized', 'hidden'], }); // panels initialize after this module on some pages: their authored states land a task later queueMicrotask(sync); // drag: the pointer's travel moves the room between the divider's two panels stack.addEventListener('pointerdown', (e: PointerEvent) => { const divider = (e.target as HTMLElement).closest?.<HTMLElement>('.border-layout-stack-divider'); if (!divider || divider.parentElement !== stack || divider.getAttribute('aria-disabled') === 'true') return; e.preventDefault(); divider.setPointerCapture(e.pointerId); divider.setAttribute('data-resizing', ''); let at = isRow(stack, side) ? e.clientX : e.clientY; const move = (ev: PointerEvent) => { const pos = isRow(stack, side) ? ev.clientX : ev.clientY; moveDivider(layout, side, divider, pos - at); at = pos; sync(); }; const end = () => { divider.removeAttribute('data-resizing'); divider.removeEventListener('pointermove', move); divider.removeEventListener('pointerup', end); divider.removeEventListener('pointercancel', end); save(layout); }; divider.addEventListener('pointermove', move); divider.addEventListener('pointerup', end); divider.addEventListener('pointercancel', end); }); // data-drill: a click on a folded level's bar, or Enter / Space on it, opens that level (the drill drops the deeper ones) const bar = (e: Event) => { if (!stack.hasAttribute('data-drill')) return null; const header = (e.target as HTMLElement).closest?.<HTMLElement>('.panel-header'); const panel = header?.parentElement; if (!panel || panel.parentElement !== stack || !panel.hasAttribute('data-minimized')) return null; if ((e.target as HTMLElement).closest('.panel-tools')) return null; return panel; }; stack.addEventListener('click', (e) => bar(e)?.api?.setState('default')); stack.addEventListener('keydown', (e: KeyboardEvent) => { if (e.key !== 'Enter' && e.key !== ' ') return; const panel = bar(e); if (!panel) return; e.preventDefault(); panel.api?.setState('default'); }); // keys: the window-splitter pattern, like the region dividers - arrows move 10 px (Shift 100), Home / End to either limit stack.addEventListener('keydown', (e: KeyboardEvent) => { const divider = (e.target as HTMLElement).closest?.<HTMLElement>('.border-layout-stack-divider'); if (!divider || divider.parentElement !== stack || divider.getAttribute('aria-disabled') === 'true') return; const step = e.shiftKey ? 100 : 10; const back = isRow(stack, side) ? 'ArrowLeft' : 'ArrowUp', fwd = isRow(stack, side) ? 'ArrowRight' : 'ArrowDown'; // a level on the east side grows to the left: ArrowLeft makes it wider, like the pointer let delta = e.key === back ? -step : e.key === fwd ? step : e.key === 'Home' ? -1e6 : e.key === 'End' ? 1e6 : 0; if (!delta) return; if (levelsOf(stack) && side === 'east' && (e.key === 'Home' || e.key === 'End')) delta = -delta; e.preventDefault(); moveDivider(layout, side, divider, delta); sync(); save(layout); }); }}// -- Persistence (data-save="key") ---------------------------------------------// one persisted store per data-save key (AGENTS.md "State through stores"):// { [side]: { size, collapsed } } - memory when storage is blocked, the plain// JSON older versions wrote adopted as-isconst saved = new Map();const savedFor = (layout) => { const key = `defuss-shadcn:border-layout:${layout.dataset.save}`; if (!saved.has(key)) { saved.set( key, persisted<Record<string, unknown>>( key, {}, { validate: (v): v is Record<string, unknown> => typeof v === 'object' && v !== null && !Array.isArray(v), }, ), ); } return saved.get(key);};function save(layout) { if (!layout.dataset.save || layout._restoring) return; const data = {}; for (const side of REGIONS) { const region = regionOf(layout, side); const stack = stackOf(region); // a stack's panels: their weights, in order const weights = stack ? panelsOf(stack).map((p) => num(p.style.getPropertyValue('--border-layout-share'), 0) || null) : null; if (!region?.classList.contains('resizer')) { if (weights) data[side] = { stack: weights }; continue; } const pane = paneOf(region); const px = Math.round(num(pane?.style[SIDES[side].size], NaN)); data[side] = { size: Number.isFinite(px) ? px : null, collapsed: region.hasAttribute('data-collapsed') }; if (weights) data[side].stack = weights; } savedFor(layout).set(data);}function restore(layout) { if (!layout.dataset.save) return; const data = savedFor(layout).value; if (!Object.keys(data).length) return; layout._restoring = true; for (const side of REGIONS) { const region = regionOf(layout, side); const saved = data[side]; if (!region || !saved) continue; if (saved.size) setSize(region, side, saved.size); if (region.classList.contains('resizer')) region.toggleAttribute('data-collapsed', !!saved.collapsed); const stack = stackOf(region); if (stack && Array.isArray(saved.stack)) panelsOf(stack).forEach((p, i) => { if (saved.stack[i]) p.style.setProperty('--border-layout-share', String(saved.stack[i])); }); } layout._restoring = false;}// -- State API -------------------------------------------------------------------/** * The markup of a state, for render(): the attributes a state writes, applied * to a detached copy of the authored markup ('default' IS the authored * markup). The live element gets the same markup from triggerStateChange - * the e2e render round trip proves they agree. */function applyMarkup(el, stateName, config) { // which regions are collapsed: none in 'default', the config's in // 'collapsed' (sizes are measured pixels - runtime-owned, see the e2e) const want = new Set(stateName === 'collapsed' ? (config?.regions ?? (config?.region ? [config.region] : [])) : []); for (const side of REGIONS) { const region = regionOf(el, side); if (region) dfDollar(region).attr('data-collapsed', want.has(side) ? '' : null); }}/** * UI side of setState. 'default' opens every region at its authored size; * 'collapsed' folds `{ regions: ['west', …] }` (or `{ region: 'west' }`) and * opens the others. */function triggerStateChange(layout, stateName, config) { if (stateName === 'default') { for (const side of REGIONS) { const region = regionOf(layout, side); if (!region) continue; region.removeAttribute('data-collapsed'); if (!region._authored) continue; // the computed maximum reflects the old layout - lift it, then re-clamp region.dataset[SIDES[side].axis === 'w' ? 'maxW' : 'maxH'] = region.dataset.maxAuthored ?? '2000'; setSize(region, side, region._authored); } clamp(layout); } else { const want = new Set(config.regions ?? (config.region ? [config.region] : [])); for (const side of REGIONS) { const region = regionOf(layout, side); if (region) region.toggleAttribute('data-collapsed', want.has(side)); } } aria(layout); save(layout);}export const borderLayoutApi = componentState({ component: 'border-layout', states: borderLayoutStates, apply: (layout, state) => { triggerStateChange(layout, state.name, state.config); syncState(layout); }, markup: (el, state) => applyMarkup(el, state.name, state.config),});df$.borderLayoutApi = borderLayoutApi;df$.borderLayoutStates = borderLayoutStates;// -- init --------------------------------------------------------------------------function init() { dfDollar('.border-layout:not([data-init])') .toArray() .forEach((layout) => { layout.dataset.init = ''; for (const side of REGIONS) { const region = regionOf(layout, side); if (!region?.classList.contains('resizer')) continue; // the resizer defaults a border region needs - authored values win const d = region.dataset; d.handles ??= SIDES[side].handle; d.axis ??= SIDES[side].axis; d.keys ??= 'edge'; d.min ??= '48'; if (d.max) d.maxAuthored = d.max; // a percentage start (width: 30%) is of the layout, not of the region's // own content-sized column (circular - it would collapse): resolve it const pane = paneOf(region); const prop = SIDES[side].size; const authored = pane?.style[prop] ?? ''; if (authored.endsWith('%')) { const inner = prop === 'width' ? layout.clientWidth : layout.clientHeight; pane.style[prop] = `${Math.round((parseFloat(authored) / 100) * inner)}px`; } region._authored = sizeOf(region, side) || null; } restore(layout); initStacks(layout); // before any drag or key: recompute the room every side may take; a drag // on a folded region unfolds it first const before = (e) => { const handle = (e.target as HTMLElement).closest?.<HTMLElement>('.resizer-handle'); if (!handle || handle.parentElement?.parentElement !== layout) return; clamp(layout); const side = REGIONS.find((s) => handle.parentElement.classList.contains(`border-layout-${s}`)); if (e.type === 'pointerdown' && side && handle.parentElement.hasAttribute('data-collapsed')) collapse(layout, side, false); }; layout.addEventListener('pointerdown', before, true); layout.addEventListener('keydown', before, true); layout.addEventListener('focusin', (e) => { before(e); aria(layout); }); // double-click or Enter on a divider folds a collapsible region const toggle = (handle) => { const region = handle.parentElement; const side = REGIONS.find((s) => region.classList.contains(`border-layout-${s}`)); if (!side || !collapsible(layout, region)) return; collapse(layout, side, !region.hasAttribute('data-collapsed')); }; layout.addEventListener('dblclick', (e) => { const handle = (e.target as HTMLElement).closest<HTMLElement>('.resizer-handle'); if (handle && handle.parentElement?.parentElement === layout) toggle(handle); }); layout.addEventListener('keydown', (e) => { const handle = (e.target as HTMLElement).closest?.<HTMLElement>('.resizer-handle'); if (e.key === 'Enter' && handle && handle.parentElement?.parentElement === layout) { e.preventDefault(); toggle(handle); } }); // every size change: splitter values, persistence layout.addEventListener('resizer-resize', (e) => { if ((e.target as HTMLElement).parentElement !== layout) return; aria(layout); save(layout); }); new ResizeObserver(() => { clamp(layout); aria(layout); }).observe(layout); // el.store + el.api (AGENTS.md "State through stores") bindComponent(layout, borderLayoutApi); syncState(layout); // the resizers may initialize after this module - label their handles then queueMicrotask(() => { clamp(layout); aria(layout); }); });}// -- df$.shadcn.borderLayout: the imperative surface ----------------------------------/** a stack by element, id or selector */const resolveStack = (target: string | HTMLElement): HTMLElement | null => { const el = typeof target === 'string' ? ((dfDollar(`#${CSS.escape(target)}`).get(0) ?? dfDollar(target).get(0)) as HTMLElement | undefined) : target; return el?.classList.contains('border-layout-stack') ? el : null;};df$.borderLayout = { /** * Folds a region away (its divider stays). * @param target - the .border-layout element, its id or a selector * @param side - the region */ collapse: (target: string | HTMLElement, side: BorderLayoutSide): void => { const l = resolve(target); if (l) collapse(l, side, true); }, /** * Brings a folded region back. * @param target - the .border-layout element, its id or a selector * @param side - the region */ expand: (target: string | HTMLElement, side: BorderLayoutSide): void => { const l = resolve(target); if (l) collapse(l, side, false); }, /** * Folds or unfolds a region. * @param target - the .border-layout element, its id or a selector * @param side - the region * @returns true when the region is collapsed now (false also when the layout has no such region) */ toggle: (target: string | HTMLElement, side: BorderLayoutSide): boolean => { const l = resolve(target); const region = l && regionOf(l, side); if (!region) return false; collapse(l, side, !region.hasAttribute('data-collapsed')); return region.hasAttribute('data-collapsed'); }, /** * Sets a region's size (clamped by the resizer's limits). * @param target - the .border-layout element, its id or a selector * @param side - the region * @param px - the width (west / east) or height (north / south) in px */ resize: (target: string | HTMLElement, side: BorderLayoutSide, px: number): void => { const l = resolve(target); const r = l && regionOf(l, side); if (r) { clamp(l); setSize(r, side, px); } }, /** * Adds a level to a stack (deep navigation): the panel goes after the others, opens, and data-keep folds the * earlier levels to bars. * @param stack - the .border-layout-stack element, its id or a selector * @param panel - the .panel element to add, or its markup * @returns the panel added, null when the stack matches none */ push: (stack: string | HTMLElement, panel: HTMLElement | string): HTMLElement | null => { const st = resolveStack(stack); if (!st) return null; const el = typeof panel === 'string' ? (dfDollar(panel).get(0) as HTMLElement | undefined) : panel; if (!el) return null; el.removeAttribute('data-minimized'); dfDollar(st).append(el); return el; }, /** * Goes back to a level: every level after it goes, and it opens. * @param stack - the .border-layout-stack element, its id or a selector * @param panel - the level to go back to: its element, id or index (0 = the outermost) * @returns the level, null when the stack or the level matches none */ pop: (stack: string | HTMLElement, panel: HTMLElement | string | number): HTMLElement | null => { const st = resolveStack(stack); if (!st) return null; const panels = panelsOf(st); const el = typeof panel === 'number' ? panels[panel] : typeof panel === 'string' ? panels.find((p) => p.id === panel) : panels.includes(panel) ? panel : undefined; if (!el) return null; dropAfter(st, el); const api = (el as HTMLElement & { api?: { setState(name: string): void } }).api; if (api) api.setState('default'); else el.removeAttribute('data-minimized'); return el; }, /** * A stack's levels, outermost first. * @param stack - the .border-layout-stack element, its id or a selector * @returns the panels with whether each is open, [] when the stack matches none */ levels: (stack: string | HTMLElement): BorderLayoutStackChangeDetail => { const st = resolveStack(stack); const panels = st ? panelsOf(st) : []; return { panels, open: panels.filter(open) }; }, /** * The current sizes: { west: 240, east: 0 (collapsed), ... }. * @param target - the .border-layout element, its id or a selector * @returns px per region the layout has - 0 for a collapsed one */ sizes: (target: string | HTMLElement): Partial<Record<BorderLayoutSide, number>> => { const l = resolve(target); const out: Partial<Record<BorderLayoutSide, number>> = {}; if (l) for (const side of REGIONS) { const r = regionOf(l, side); if (r) out[side] = sizeOf(r, side); } return out; },};init();new MutationObserver(init).observe(document, { childList: true, subtree: true });Comments, ideas or improvements? Edit this page's source on GitHub