Skip to content

An open source design system that's fully customizable and agent ready

TypeScript

feat(treelist): flush leaves in all-leaf groups + themeable inter-row gap (#4540)

freddymeta742706583af7
diff --git a/.changeset/treelist-flush-leaves-row-gap.md b/.changeset/treelist-flush-leaves-row-gap.md
new file mode 100644
index 0000000000..011c16f91a
--- /dev/null
+++ b/.changeset/treelist-flush-leaves-row-gap.md
@@ -0,0 +1,6 @@
+---
+'@astryxdesign/core': patch
+---
+
+[feat] TreeList: two additive changes. (1) A fully flat tree — one with no expandable items at all — now renders its rows flush instead of reserving an empty chevron-alignment column that nothing lines up under; any tree that has at least one expandable item keeps the same per-level alignment as before, so only fully flat trees change shape. (2) Adds a themeable `--tree-list-row-gap` for the inter-row gap, defaulting to a subtle `2px` (`var(--spacing-0-5)`) separation — matching the inter-row gap `List` and `DropdownMenu` already ship — so this shifts the default spacing of every tree by that amount; set it on the `tree-list` target to widen or close it. The gap rides collapse-proof `padding-block` on the row wrapper (not the paintable `tree-list-item` target), and the connector guides span it automatically without overhanging the last row. (#4540)
+@freddymeta
diff --git a/packages/core/src/TreeList/TreeList.doc.mjs b/packages/core/src/TreeList/TreeList.doc.mjs
index 4658039df7..a9e8860748 100644
--- a/packages/core/src/TreeList/TreeList.doc.mjs
+++ b/packages/core/src/TreeList/TreeList.doc.mjs
@@ -32,6 +32,7 @@ export const docs = {
],
vars: [
{name: '--tree-list-indent', description: 'Per-level indentation step. Each nesting level indents its rows by this distance, and the guide lines follow it so they stay aligned. Set it on the `tree-list` target to retune the metric (e.g. `var(--spacing-5)` for a wider indent).', default: 'var(--spacing-4)'},
+ {name: '--tree-list-row-gap', description: 'Vertical gap between adjacent rows. Default `2px` (var(--spacing-0-5)) gives a subtle separation; set it on the `tree-list` target to widen or close the gap. The connector guides span the gap automatically (the line stays continuous) and do not overhang the last row, so no guide-height tuning is needed.', default: 'var(--spacing-0-5)'},
],
},
components: [
@@ -82,6 +83,7 @@ export const docs = {
bestPractices: [
{guidance: true, description: 'Provide meaningful labels and icons for each node to make the hierarchy easy to scan.'},
{guidance: true, description: 'Pre-expand important branches so users see key content immediately.'},
+ {guidance: true, description: 'Leaf rows reserve space for a chevron column whenever the tree has any expandable item to line up under; only a fully flat tree (no expandable items at all) renders its rows flush. Rely on this rather than nudging indentation with custom CSS.'},
{guidance: false, description: 'Nest more than 4–5 levels deep; flatten the structure or use a different pattern.'},
{guidance: false, description: 'Use a tree for flat, non-hierarchical data; use a List instead.'},
],
@@ -109,6 +111,7 @@ export const docsZh = {
],
vars: [
{name: '--tree-list-indent', description: '每级缩进步长。每个嵌套层级的行按此距离缩进,引导线随之对齐。在 `tree-list` 目标上设置以调整该度量(例如用 `var(--spacing-5)` 获得更宽的缩进)。', default: 'var(--spacing-4)'},
+ {name: '--tree-list-row-gap', description: '相邻行之间的垂直间距。默认 `2px`(var(--spacing-0-5))提供细微的分隔;在 `tree-list` 目标上设置以加宽或关闭间距。连接引导线会自动跨越该间距(线保持连续)且不会超出最后一行,因此无需调整引导线高度。', default: 'var(--spacing-0-5)'},
],
},
components: [
@@ -159,6 +162,7 @@ export const docsZh = {
bestPractices: [
{guidance: true, description: 'Provide meaningful labels and icons for each node to make the hierarchy easy to scan.'},
{guidance: true, description: 'Pre-expand important branches so users see key content immediately.'},
+ {guidance: true, description: 'Leaf rows reserve space for a chevron column whenever the tree has any expandable item to line up under; only a fully flat tree (no expandable items at all) renders its rows flush. Rely on this rather than nudging indentation with custom CSS.'},
{guidance: false, description: 'Nest more than 4–5 levels deep; flatten the structure or use a different pattern.'},
{guidance: false, description: 'Use a tree for flat, non-hierarchical data; use a List instead.'},
],
@@ -175,6 +179,7 @@ export const docsDense = {
bestPractices: [
{guidance: true, description: 'Provide meaningful labels and icons for each node to make the hierarchy easy to scan.'},
{guidance: true, description: 'Pre-expand important branches so users see key content immediately.'},
+ {guidance: true, description: 'Leaf rows reserve space for a chevron column whenever the tree has any expandable item to line up under; only a fully flat tree (no expandable items at all) renders its rows flush. Rely on this rather than nudging indentation with custom CSS.'},
{guidance: false, description: 'Nest more than 4–5 levels deep; flatten the structure or use a different pattern.'},
{guidance: false, description: 'Use a tree for flat, non-hierarchical data; use a List instead.'},
],
diff --git a/packages/core/src/TreeList/TreeList.test.tsx b/packages/core/src/TreeList/TreeList.test.tsx
index f1317dcc39..f570da2c64 100644
--- a/packages/core/src/TreeList/TreeList.test.tsx
+++ b/packages/core/src/TreeList/TreeList.test.tsx
@@ -21,6 +21,29 @@ function generateThemeTestCSS(theme: Parameters<typeof generateThemeCSS>[0]) {
const {prose, component} = generateThemeCSS(theme);
return [prose, component].filter(Boolean).join('\n\n');
}
+
+/**
+ * Concatenate all StyleX-injected CSS (both CSSOM sheets and <style> text) so
+ * tests can assert on compiled stylesheet rules — jsdom does not resolve the
+ * @layer cascade or compute layout, so structural CSS assertions read the
+ * generated declarations directly.
+ */
+function collectCssText(): string {
+ let out = '';
+ for (const sheet of Array.from(document.styleSheets)) {
+ try {
+ for (const rule of Array.from(sheet.cssRules)) {
+ out += rule.cssText + '\n';
+ }
+ } catch {
+ // ignore cross-origin sheets
+ }
+ }
+ out += Array.from(document.querySelectorAll('style'))
+ .map(s => s.textContent || '')
+ .join('\n');
+ return out;
+}
const simpleItems: TreeListItemData[] = [
{id: 'a', label: 'Item A'},
{id: 'b', label: 'Item B'},
@@ -548,6 +571,182 @@ describe('TreeList', () => {
});
});
+ // ===========================================================================
+ // Leaf chevron-column offset (group-expandable-sibling awareness)
+ // ===========================================================================
+
+ describe('leaf chevron-column offset', () => {
+ // A row publishes its indent as the inline `--_tree-indent` custom property.
+ // A leaf that reserves the chevron column adds a fixed offset
+ // (chevron width + gap) on top of its level indent; a flush leaf does not.
+ // The reserved column is expressed as the literal `+ <spacing-4> + <spacing-2>`
+ // suffix in the calc(), so its presence is what we assert (jsdom does not
+ // resolve the token values, so we check the structure, not pixels).
+ const indentStyleOf = (text: string): string => {
+ const li = screen.getByText(text).closest('li')!;
+ const styled = li.querySelector('[style*="--_tree-indent"]');
+ return styled?.getAttribute('style') ?? '';
+ };
+ // A reserved chevron column adds two extra terms to the indent calc()
+ // beyond the single `level * var(--tree-list-indent)` term.
+ const reservesColumn = (text: string): boolean => {
+ const style = indentStyleOf(text);
+ // count the `var(` occurrences inside --_tree-indent: a flush row has
+ // exactly one (the indent step); a reserving leaf adds the chevron
+ // width + gap tokens, so it has more.
+ const m = /--_tree-indent:\s*calc\(([^;]*)\)/.exec(style);
+ const body = m?.[1] ?? '';
+ return (body.match(/\bvar\(/g)?.length ?? 0) > 1 || body.includes('+');
+ };
+
+ it('a leaf in a mixed group reserves the chevron column (aligns under its expandable sibling)', () => {
+ // Group: [Parent (has children), Sibling (leaf)] → Sibling must line up
+ // under Parent's caret, so it keeps the chevron-column offset.
+ render(<TreeList items={nestedItems} />);
+ expect(reservesColumn('Sibling')).toBe(true);
+ });
+
+ it('a leaf under an expandable ancestor reserves the chevron column even when its own group is all leaves', () => {
+ // 'Root' → 'Mid' → 'Leaf'; 'Leaf' is the only item in its immediate
+ // group, but the tree has carets (Root, Mid), so Leaf must reserve the
+ // chevron column to stay indented past its parent's label. Flushing it
+ // here would push it left of Mid's label — the all-leaf-group bug.
+ render(<TreeList items={deepItems} variant="noGuides" />);
+ expect(reservesColumn('Leaf')).toBe(true);
+ });
+
+ it("an expanded parent's all-leaf children reserve the chevron column (do not flush left of the parent label)", () => {
+ // Regression: Parent (caret) → [Child 1, Child 2] is an all-leaf group
+ // nested under an expandable parent. Per-group flushing wrongly dropped
+ // these children's chevron column, pushing them LEFT of Parent's own
+ // label. Because the tree has a caret, they must reserve the column and
+ // stay indented past Parent.
+ render(<TreeList items={nestedItemsExpanded} />);
+ expect(reservesColumn('Child 1')).toBe(true);
+ expect(reservesColumn('Child 2')).toBe(true);
+ });
+
+ it('every row in a flat (all-leaf) tree sits flush — no chevron column reserved', () => {
+ render(<TreeList items={flatItems} />);
+ expect(reservesColumn('Apple')).toBe(false);
+ expect(reservesColumn('Banana')).toBe(false);
+ expect(reservesColumn('Cherry')).toBe(false);
+ });
+
+ it('leaves flush in an all-leaf group have the same indent structure as a parent at that level', () => {
+ // In a mixed group the reserving leaf indent has the extra terms; in an
+ // all-leaf group the leaf indent is the bare level step, exactly like a
+ // parent row's indent.
+ render(<TreeList items={flatItems} />);
+ const flush = indentStyleOf('Apple');
+ // bare level step: one var(--tree-list-indent), no additive chevron terms
+ expect(flush).toContain('var(--tree-list-indent)');
+ expect(/--_tree-indent:\s*calc\([^;]*\+[^;]*\)/.test(flush)).toBe(false);
+ });
+ });
+
+ // ===========================================================================
+ // Inter-row gap lever (--tree-list-row-gap) + guide spanning
+ // ===========================================================================
+
+ describe('row gap lever', () => {
+ it('defaults the row gap to a subtle 2px separation', () => {
+ // The lever is published on the tree-list root; its default is
+ // --spacing-0-5 (2px) so rows have a light separation out of the box. A
+ // theme can widen or close it via the tree-list target. jsdom does not
+ // resolve token vars, so the declared value is the --spacing-0-5 token.
+ render(<TreeList items={simpleItems} data-testid="tree" />);
+ const root = screen.getByTestId('tree');
+ expect(
+ getComputedStyle(root).getPropertyValue('--tree-list-row-gap').trim(),
+ ).toBe('var(--spacing-0-5)');
+ });
+
+ it('lets a theme open a row gap via the tree-list target', () => {
+ // jsdom cannot resolve the @layer cascade, so the generated CSS is what
+ // proves the override reaches the lever.
+ const theme = defineTheme({
+ name: 'tree-list-row-gap-test',
+ components: {
+ 'tree-list': {
+ base: {'--tree-list-row-gap': 'var(--spacing-1)'},
+ },
+ },
+ });
+ const css = generateThemeTestCSS(theme);
+ expect(css).toContain('.astryx-tree-list {');
+ expect(css).toContain('--tree-list-row-gap: var(--spacing-1)');
+ });
+
+ it('the guide of a row with a sibling below spans into it (verticalFull)', () => {
+ // A row that is NOT last in its group bridges the 1px hairline into the
+ // next contiguous sibling so the connector reads as one continuous line.
+ // Assert the APPLIED class on that row's own connector — not a global
+ // stylesheet regex — so the isLast ? verticalLast : verticalFull branch
+ // is actually exercised (Child 1 has Child 2 below it).
+ render(<TreeList items={nestedItemsExpanded} />);
+ const child1 = screen.getByText('Child 1').closest('li')!;
+ const guide = child1.firstElementChild!.querySelector(
+ '.astryx-tree-list-guide',
+ );
+ expect(guide).not.toBeNull();
+ expect(guide!.className).toContain('verticalFull');
+ expect(guide!.className).not.toContain('verticalLast');
+ });
+
+ it('clamps the last-in-group guide so it does not overhang the gap (verticalLast)', () => {
+ // The last row in a group has nothing below it, so its connector must NOT
+ // run through the row wrapper's bottom padding into empty space — it uses
+ // verticalLast, which subtracts half the row gap. Assert the applied class
+ // on the last child's own connector (Child 2 is last in its group), so a
+ // reverted branch is caught.
+ render(<TreeList items={nestedItemsExpanded} />);
+ const child2 = screen.getByText('Child 2').closest('li')!;
+ const guide = child2.firstElementChild!.querySelector(
+ '.astryx-tree-list-guide',
+ );
+ expect(guide).not.toBeNull();
+ expect(guide!.className).toContain('verticalLast');
+ expect(guide!.className).not.toContain('verticalFull');
+ });
+
+ it('carries the inter-row gap as collapse-proof padding on the row wrapper, not the paint target', () => {
+ // Finding from review: the gap must be `padding-block` (which cannot
+ // collapse) on the row WRAPPER, not `margin-block` on the row box — a
+ // margin there collapses through the position:relative wrapper and the
+ // <li>, delivering only half the configured gap. It also must not sit on
+ // `tree-list-item`, which is a paint seam (per the theming-target
+ // guidelines): layout longhands do not belong on a paintable target.
+ const {container} = render(<TreeList items={simpleItems} />);
+ const item = container.querySelector<HTMLElement>(
+ '.astryx-tree-list-item',
+ );
+ expect(item).not.toBeNull();
+ const rowWrapper = item!.parentElement!;
+
+ const rules = collectCssText();
+ // Map the rowWrapper's compiled class to its declaration block and assert
+ // it declares padding-block from the row-gap lever (half above/below).
+ const rowWrapperClass = Array.from(rowWrapper.classList).find(c =>
+ c.includes('rowWrapper'),
+ );
+ expect(rowWrapperClass).toBeDefined();
+ // The gap rides padding-block (collapse-proof), keyed off the lever.
+ expect(rules).toMatch(
+ /padding-block:\s*calc\(\s*var\(--tree-list-row-gap[^)]*\)\s*\/\s*2\s*\)/,
+ );
+ // And the paint target (tree-list-item / contentWrapper) must NOT carry a
+ // margin-block gap — the layout seam has moved off the paintable element.
+ const itemClass = Array.from(item!.classList).find(c =>
+ c.includes('contentWrapper'),
+ );
+ expect(itemClass).toBeDefined();
+ expect(rules).not.toMatch(
+ /margin-block:\s*calc\([^;]*var\(--tree-list-row-gap/,
+ );
+ });
+ });
+
// ===========================================================================
// xds class name
// ===========================================================================
diff --git a/packages/core/src/TreeList/TreeList.tsx b/packages/core/src/TreeList/TreeList.tsx
index ffea950eb7..70cc8cc4d7 100644
--- a/packages/core/src/TreeList/TreeList.tsx
+++ b/packages/core/src/TreeList/TreeList.tsx
@@ -88,6 +88,13 @@ const styles = stylex.create({
// on the `tree-list` target, and both the row margins (TreeListItem) and
// the guide-line offsets (TreeListBranches) read it so they stay aligned.
'--tree-list-indent': spacingVars['--spacing-4'],
+ // Vertical gap between adjacent rows. Public, themeable lever (default
+ // `--spacing-0-5` = 2px for a subtle separation between rows). A theme sets
+ // it on the `tree-list` target to widen or close the gap; the guide
+ // connector spans the gap natively (see TreeListBranches) so the line stays
+ // continuous and does not overhang the last row — no consumer-side guide
+ // tuning needed.
+ '--tree-list-row-gap': spacingVars['--spacing-0-5'],
},
list: {
margin: 0,
@@ -250,11 +257,25 @@ export function TreeList({
hasRovingTabIndex: true,
});
+ const hasExpandableItems = items.some(
+ item => item.children != null && item.children.length > 0,
+ );
+
function renderItems(
items: TreeListItemData[],
nestedLevel: number,
ancestorsIsLast: ReadonlyArray<boolean>,
): ReactNode {
+ // A leaf reserves the chevron column (so its label lines up under a parent's
+ // caret) whenever the tree contains ANY expandable item — i.e. whenever a
+ // caret exists somewhere to align under. This is a whole-tree property, not
+ // a per-group one: a leaf nested under an expandable ancestor must still
+ // reserve the column so it stays indented past its parent's label, even if
+ // its own immediate group happens to be all leaves. Only a fully flat tree
+ // (no expandable items anywhere) has no caret to align under, so its rows
+ // sit flush. Because any expandable descendant forces its whole ancestor
+ // chain to be expandable, "the tree has an expandable item" is equivalent to
+ // "the root group has an expandable item" — checked once at the root.
return items.map((item, index) => {
const isLast = index === items.length - 1;
const isExpanded = expandedKeysOverride.has(item.id)
@@ -284,6 +305,7 @@ export function TreeList({
startContent={item.startContent}
endContent={item.endContent}
hasChildren={hasChildren}
+ hasExpandableItems={hasExpandableItems}
onClick={item.onClick}
href={item.href}
target={item.target}
diff --git a/packages/core/src/TreeList/TreeListBranches.tsx b/packages/core/src/TreeList/TreeListBranches.tsx
index f93ec9605e..1a1ece606f 100644
--- a/packages/core/src/TreeList/TreeListBranches.tsx
+++ b/packages/core/src/TreeList/TreeListBranches.tsx
@@ -46,9 +46,24 @@ const styles = stylex.create({
width: LINE_WIDTH,
backgroundColor: colorVars['--color-border-emphasized'],
},
+ // Guide segment spanning the full <li>. The row box's inter-row gap now lives
+ // INSIDE the <li> (as `padding-block` on the row wrapper), so `height: 100%`
+ // already covers it — the segment only needs the original `1px` to bridge the
+ // hairline into the next contiguous sibling so the connector reads as one
+ // continuous line. Independent of `--tree-list-row-gap`: the gap is absorbed
+ // by the <li> height, not added on top here.
verticalFull: {
height: 'calc(100% + 1px)',
},
+ // Last-in-group connector: nothing sits below, so the segment must not run
+ // through the row wrapper's bottom `padding-block` (`--tree-list-row-gap` / 2)
+ // into empty space. Clamp it back by that half-gap so it ends exactly at the
+ // row box's bottom edge. At the default `--spacing-0-5` gap this trims the
+ // 1px of bottom padding; at `0px` it is exactly `100%` — no overhang at any
+ // gap.
+ verticalLast: {
+ height: 'calc(100% - var(--tree-list-row-gap, 0px) / 2)',
+ },
});
// =============================================================================
@@ -76,7 +91,7 @@ interface TreeListBranchesProps {
*/
export function TreeListBranches({
ancestorsIsLast,
- isLast: _isLast,
+ isLast,
nestedLevel,
}: TreeListBranchesProps) {
return (
@@ -117,7 +132,15 @@ export function TreeListBranches({
<div
{...mergeProps(
themeProps('tree-list-guide'),
- stylex.props(styles.verticalLine, styles.verticalFull),
+ // The last item in a group has no sibling below, so its connector
+ // is clamped to the row box's bottom edge (verticalLast) instead
+ // of bridging into the inter-row gap — no overhang into empty
+ // space. Every other row bridges the gap (verticalFull) so the
+ // line stays continuous down to the next sibling.
+ stylex.props(
+ styles.verticalLine,
+ isLast ? styles.verticalLast : styles.verticalFull,
+ ),
)}
/>
</div>
diff --git a/packages/core/src/TreeList/TreeListItem.tsx b/packages/core/src/TreeList/TreeListItem.tsx
index 5d4c57940a..f1a06fd9b2 100644
--- a/packages/core/src/TreeList/TreeListItem.tsx
+++ b/packages/core/src/TreeList/TreeListItem.tsx
@@ -70,6 +70,17 @@ const styles = stylex.create({
},
rowWrapper: {
position: 'relative',
+ // Inter-row gap. Half the public `--tree-list-row-gap` lever sits above and
+ // half below the row box; because this is PADDING (not margin) it cannot
+ // collapse, so adjacent rows end up a full gap apart — and it rides the
+ // `rowWrapper`, which carries no theme target, so the paintable
+ // `tree-list-item` stays a pure paint seam (layout lives off it). The <li>s
+ // stay contiguous — the gap is padding INSIDE each <li>, not space between
+ // them — so the per-<li> connector guide can still span it and read as a
+ // continuous line (see TreeListBranches). The lever's default is a subtle
+ // `--spacing-0-5` (2px, set on the tree-list root); a theme widens or closes
+ // it via the `tree-list` target.
+ paddingBlock: 'calc(var(--tree-list-row-gap, 0px) / 2)',
},
contentWrapper: {
borderRadius: radiusVars['--radius-element'],
@@ -292,6 +303,16 @@ export interface TreeListItemInternalProps {
isDisabled?: boolean;
isSelected?: boolean;
hasChildren: boolean;
+ /**
+ * Whether the tree contains at least one expandable item anywhere (i.e. a
+ * caret exists somewhere to align labels under). A leaf reserves the chevron
+ * column — the extra offset that lines its label up past an expandable
+ * ancestor/sibling's caret — whenever this is true, so it stays indented
+ * beyond its parent's label. Only a fully flat tree (no expandable items at
+ * all) has no caret to align under, so its rows sit flush (no chevron-column
+ * offset). Computed once for the whole tree by TreeList.
+ */
+ hasExpandableItems: boolean;
nestedLevel: number;
isLast: boolean;
ancestorsIsLast: ReadonlyArray<boolean>;
@@ -334,6 +355,7 @@ export function TreeListItem({
isDisabled = false,
isSelected = false,
hasChildren,
+ hasExpandableItems,
nestedLevel,
isLast,
ancestorsIsLast,
@@ -385,15 +407,19 @@ export function TreeListItem({
// Per-level indent distance. The per-level step is the public, themeable
// `--tree-list-indent` lever (default `--spacing-4`, set on the tree-list
- // root). Leaves add a fixed chevron-column offset (chevron width + gap) so
- // their labels line up with sibling parents' labels; that offset is tied to
+ // root). A leaf adds a fixed chevron-column offset (chevron width + gap) so
+ // its label lines up past an expandable ancestor/sibling's caret — but ONLY
+ // when the tree actually contains an expandable item somewhere. In a fully
+ // flat tree there is no caret to align under, so the offset is pointless and
+ // every row sits flush, like a parent at that level. That offset is tied to
// the chevron's own dimensions, not the indent step, so it does not scale
// with the lever. Published as the private `--_tree-indent` and consumed by
// `contentWrapper`'s stylesheet `margin-inline-start` (kept out of the inline
// style so the theme layer can override it — see #4308).
- const indentDistance = hasChildren
- ? `calc(${nestedLevel} * var(--tree-list-indent))`
- : `calc(${nestedLevel} * var(--tree-list-indent) + ${spacingVars['--spacing-4']} + ${spacingVars['--spacing-2']})`;
+ const reservesChevronColumn = !hasChildren && hasExpandableItems;
+ const indentDistance = reservesChevronColumn
+ ? `calc(${nestedLevel} * var(--tree-list-indent) + ${spacingVars['--spacing-4']} + ${spacingVars['--spacing-2']})`
+ : `calc(${nestedLevel} * var(--tree-list-indent))`;
const indentStyle: IndentStyle = {'--_tree-indent': indentDistance};
const labelAndDescription = (