Skip to content
Merged
Show file tree
Hide file tree
Changes from 8 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
7 changes: 7 additions & 0 deletions .changeset/tree-list-expand-motion.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,7 @@
---
'@astryxdesign/core': patch
---

[feat] Under a coarse primary pointer, expanding a `TreeList` row glides the rows below it to their new places on the shared layout glide while its children fade in on the same timing, so the tree moves as one. A collapse fades the children out as the rows below glide up, and the chevron turns on that timing. The rows used to appear and leave in a single frame. Without an `animatedLayout` handle the motion stays inside the tree, so content after the tree takes its place at once, and the tree clips its bottom edge while it moves so no row paints over that content; pass a handle for it to glide too. The guide lines beside a group now show and hide with its rows. With reduced motion on and a finger, the children fade in where they land. With a mouse the rows still change at once. Under every pointer, a guide line now ends at the last row it joins instead of running on beside an expanded last row's children.

@vjeux
19 changes: 19 additions & 0 deletions apps/storybook/stories/TreeList.stories.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -76,6 +76,25 @@ export const Basic: Story = {
},
};

export const WithContentBelow: Story = {
render: () => (
<VStack gap={4}>
<TreeList items={fileTreeItems} />
<Button label="Open folder" onClick={() => {}} />
</VStack>
),
parameters: {
docs: {
description: {
story:
'Content after the tree takes its new place by layout when a ' +
"folder expands or collapses; under a finger only the tree's own " +
'rows animate.',
},
},
},
};

export const FullyExpanded: Story = {
args: {
items: [
Expand Down
4 changes: 3 additions & 1 deletion docs/architecture/react-component-runtime.md
Original file line number Diff line number Diff line change
Expand Up @@ -253,7 +253,9 @@ those contracts.
side nav collapse or expand (`component:AppShell` FR17, `component:SideNav`
FR6), each making its copy through the swap. A resize controller also holds
its own handle for a LayoutPanel's collapse and open, with no copy
(`component:Resizable` FR8). The module may also play
(`component:Resizable` FR8). Under a coarse pointer, a TreeList with no handle
from the app holds its own for its own expand and collapse, with no copy
(`component:TreeList` FR8). The module may also play
caller-supplied frames on elements the page already renders, on the one
shared motion, with no copy, releasing them when the motion ends; AppShell's
content surface uses this to cover an expand's gap when its old wrap is not
Expand Down
7 changes: 4 additions & 3 deletions docs/specs/AST-105-animated-layout/spec.md
Original file line number Diff line number Diff line change
Expand Up @@ -66,12 +66,13 @@ const animatedLayout = useAnimatedLayout({containerRef: scrollRef});
`animatedLayout` prop or option.
- **FR2 — Without a handle, nothing changes.** A component without a handle
keeps its behavior: the changed element shows its change as its own record
says, and content after it takes its place at once. AppShell's content area and
the SideNav rail animate their own change during a side nav collapse or
says, and content after it takes its place at once. AppShell's content area
and the SideNav rail animate their own change during a side nav collapse or
expand, and a resizable pane a LayoutPanel renders animates its own collapse
and open, as their records state (`component:AppShell` FR17,
`component:SideNav` FR6, `component:Resizable` FR8, `component:LayoutPanel`
FR7).
FR7). Under a coarse pointer, a TreeList with no handle from the app animates
its own expand and collapse inside the tree (`component:TreeList` FR8).
- **FR3 — The content after a change glides within the area.** For any change
a component holding the handle reports, such as a disclosure opening,
content loading in, a message appearing, or an item inserted or removed,
Expand Down
56 changes: 31 additions & 25 deletions docs/specs/components/TreeList/TreeList.spec.md

Large diffs are not rendered by default.

101 changes: 101 additions & 0 deletions packages/core/src/List/__tests__/reducedMotion.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,101 @@
// Copyright (c) Meta Platforms, Inc. and affiliates.

/**
* @file reducedMotion.ts
* @input The interaction harness's held animations
* @output `expectReducedMotionCrossFade`: the browser check of the Reduce
* Motion cross-fade over what a change started
* @position Test helper for the TreeList interaction specs. Each case runs
* under Reduce Motion with a coarse pointer (a finger).
*/

import {expect} from '@astryxdesign/a11y-spec/playwright';
import type {HeldAnimation} from '@astryxdesign/interaction-harness';

/** The limit on a touch presentation's cross-fade under Reduce Motion. */
const REDUCED_MOTION_FADE_MS = 200;

const TIMING_KEYS = new Set([
'offset',
'computedOffset',
'easing',
'composite',
]);

/** Properties that move, turn or scale an element. */
const TRAVEL = new Set(['translate', 'rotate', 'scale', 'transform']);

/** The properties an animation's keyframes change. */
function animatedProperties(animation: HeldAnimation): string[] {
const properties = new Set<string>();
for (const frame of animation.keyframes) {
for (const key of Object.keys(frame)) {
if (!TIMING_KEYS.has(key)) {
properties.add(key);
}
}
}
return [...properties];
}

/**
* Whether the animation only lands `property` at a new value, rather than
* moving it through the values between. A step lands it: the value changes
* between keyframes at the same offset, or under a step easing.
*/
function onlyLands(animation: HeldAnimation, property: string): boolean {
const frames = animation.keyframes.filter(frame => property in frame);
for (let index = 0; index + 1 < frames.length; index += 1) {
const from = frames[index];
const to = frames[index + 1];
if (String(from[property]) === String(to[property])) {
continue;
}
const sameOffset =
Number(from.computedOffset) === Number(to.computedOffset);
const easing = typeof from.easing === 'string' ? from.easing : '';
const stepped = /^step|steps\(/.test(easing);
if (!sameOffset && !stepped) {
return false;
}
}
return true;
}

/**
* The Reduce Motion cross-fade under a coarse pointer. At least one opacity
* animation runs, and its curve ends within 200 ms. Nothing travels, scales
* or resizes on the way, though an element may land at its new place in one
* step, hidden by the fade. Nothing but opacity animates. `held` is what
* `holdAnimations` returned right after the change.
*/
export function expectReducedMotionCrossFade(
held: ReadonlyArray<HeldAnimation>,
): void {
const summary = JSON.stringify(
held.map(animation => ({
target: animation.target,
properties: animatedProperties(animation),
curveEndMs: animation.curveEndMs,
})),
);
let fades = 0;
for (const animation of held) {
for (const property of animatedProperties(animation)) {
if (property === 'opacity') {
fades += 1;
expect(animation.curveEndMs, summary).toBeGreaterThan(0);
expect(animation.curveEndMs, summary).toBeLessThanOrEqual(
REDUCED_MOTION_FADE_MS + 1,
);
} else if (TRAVEL.has(property)) {
expect(onlyLands(animation, property), `${property}: ${summary}`).toBe(
true,
);
} else {
expect(property, summary).toBe('opacity');
}
}
}
expect(fades, summary).toBeGreaterThan(0);
}
2 changes: 1 addition & 1 deletion packages/core/src/TreeList/TreeList.doc.mjs
Original file line number Diff line number Diff line change
Expand Up @@ -143,7 +143,7 @@ export const docs = {
usage: {
anatomy,
description:
'An expandable tree structure for displaying hierarchical data with branch connector lines. Use it for file explorers, nested category browsers, or any interface that visualizes parent-child relationships.',
'An expandable tree structure for displaying hierarchical data with branch connector lines. Use it for file explorers, nested category browsers, or any interface that visualizes parent-child relationships. Under a finger, expanding a row glides the rows below it while its children fade in on the same timing, and a collapse plays it back; pass an `animatedLayout` handle for content after the tree to glide too.',
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.'},
Expand Down
61 changes: 57 additions & 4 deletions packages/core/src/TreeList/TreeList.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -26,7 +26,7 @@ import {
} from 'react';
import * as stylex from '@stylexjs/stylex';
import {isRenderable} from '../utils/isRenderable';
import {spacingVars} from '../theme/tokens.stylex';
import {focusVars, spacingVars} from '../theme/tokens.stylex';
import {mergeProps} from '../utils';
import type {BaseProps} from '../BaseProps';
import {TreeListItem} from './TreeListItem';
Expand All @@ -38,6 +38,7 @@ import type {
import {themeProps} from '../utils/themeProps';
import {useTreeFocusInternal} from '../hooks/useTreeFocus';
import {LayoutChangeSnapshot} from '../motion/LayoutChangeSnapshot';
import {useTouchPresentation} from '../utils/touchPresentation';
import {
moveFocusLeftBehind,
noteFocusWithin,
Expand All @@ -46,6 +47,7 @@ import {
import {useInteractionModalityTracking} from '../utils/interactionModality';
import {useFocusLeavingChange} from '../utils/useFocusLeavingChange';
import {useMergedRefs} from '../hooks/useMergedRefs';
import {useAnimatedLayout} from '../hooks/useAnimatedLayout';
import {
applyLayoutChangeTransition,
holdLayoutExit,
Expand All @@ -56,6 +58,46 @@ import {
type LayoutChange,
} from '../motion/animatedLayout';

/**
* The clip a tree with no handle takes while it moves. Rows that glide up into
* a shorter tree then show as they enter it. So they never paint over the
* content after it, as in a table view that clips to its bounds. Only the
* bottom edge clips, past the reach of a row's focus ring.
*/
Comment thread
astracat-bot[bot] marked this conversation as resolved.
Resolved
const MOVING_CLIP = `inset(-100vmax -100vmax calc(-1 * (${focusVars['--focus-outline-width']} + ${focusVars['--focus-outline-offset']})) -100vmax)`;

const clipGenerations = new WeakMap<HTMLElement, number>();

/** Clips `tree` with `MOVING_CLIP` until each finite motion in it settles. */
function clipWhileMoving(tree: HTMLElement): void {
if (typeof tree.getAnimations !== 'function') {
return;
}
const moving = tree
.getAnimations({subtree: true})
.filter(
animation =>
animation.playState === 'running' &&
Number.isFinite(
animation.effect?.getComputedTiming().endTime ?? Infinity,
),
);
if (moving.length === 0) {
return;
}
const generation = (clipGenerations.get(tree) ?? 0) + 1;
clipGenerations.set(tree, generation);
tree.style.setProperty('clip-path', MOVING_CLIP);
void Promise.allSettled(
moving.map(async animation => animation.finished),
).then(() => {
if (clipGenerations.get(tree) === generation) {
clipGenerations.delete(tree);
tree.style.removeProperty('clip-path');
}
});
}

// =============================================================================
// Types
// =============================================================================
Expand Down Expand Up @@ -246,7 +288,7 @@ export function TreeList({
'aria-labelledby': ariaLabelledby,
ref,
onKeyDown: onKeyDownProp,
animatedLayout,
animatedLayout: animatedLayoutProp,
...restProps
}: TreeListProps) {
const headerId = useId();
Expand All @@ -270,6 +312,14 @@ export function TreeList({
// (`architecture:react-component-runtime` INV12). Read through a ref
// because the tree element comes from the focus hook below.
const treeElementRef = useRef<HTMLUListElement | null>(null);
const {isTouch} = useTouchPresentation();
// Under a finger, a tree with no handle animates inside itself. The rows
// after a toggled row glide while its group fades on the same timing.
// Content after the tree takes its place at once, because only an app's own
// handle moves it.
const ownLayout = useAnimatedLayout({containerRef: treeElementRef});
const animatedLayout =
animatedLayoutProp ?? (isTouch ? ownLayout : undefined);
// The rows expanded now, whatever expanded them (a click, the keyboard, or
// `isExpanded` changed in `items`).
const expandedIds = useMemo(() => {
Expand Down Expand Up @@ -557,7 +607,11 @@ export function TreeList({
endAll();
}
}
}, [expandedIds, animatedLayout, endExit]);
const tree = treeElementRef.current;
if (pendings.length > 0 && animatedLayout === ownLayout && tree != null) {
clipWhileMoving(tree);
}
}, [expandedIds, animatedLayout, ownLayout, endExit]);

const {treeRef, handleKeyDown, handleFocus, takeTabStop} =
useTreeFocusInternal<HTMLUListElement>({
Expand Down Expand Up @@ -595,7 +649,6 @@ export function TreeList({
const hasExpandableItems = items.some(
item => item.children != null && item.children.length > 0,
);

function renderItems(
items: TreeListItemData[],
nestedLevel: number,
Expand Down
32 changes: 19 additions & 13 deletions packages/core/src/TreeList/TreeListBranches.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -40,6 +40,9 @@ const styles = stylex.create({
// and let pointer input fall through to the row underneath.
container: {
height: '100%',
// From the row wrapper's top edge, so a line spans the gap padding above
// the row too.
insetBlockStart: 0,
position: 'absolute',
width: GUIDE_COLUMN_WIDTH,
zIndex: 1,
Expand All @@ -54,12 +57,12 @@ 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.
// Guide segment spanning its row wrapper. The row box's inter-row gap lives
// inside the row wrapper, as its `padding-block`. So `height: 100%` already
// covers it. The segment adds only the original `1px`, which bridges the
// hairline into the next sibling, so the connector reads as one line.
// Independent of `--tree-list-row-gap`: the gap is absorbed by the row
// wrapper's height, not added on top here.
verticalFull: {
height: 'calc(100% + 1px)',
},
Expand Down Expand Up @@ -90,7 +93,8 @@ interface TreeListBranchesProps {

/**
* Renders vertical lines showing parent-child relationships in the tree.
* Positioned in a full-height container to span the entire item including children.
* Each line spans its own row. An expanded row's children draw the lines
* beside them, so the lines show and hide with its group.
*
* The line element carries the stable `astryx-tree-list-guide` theme target so a
* theme can recolor or hide the connectors via `defineTheme` (e.g.
Expand All @@ -104,14 +108,16 @@ export function TreeListBranches({
}: TreeListBranchesProps) {
return (
<>
{ancestorsIsLast.map((ancestorIsLast, level) => {
{ancestorsIsLast.map((_, level) => {
const branchOffset = `calc(${GUIDE_COLUMN_START} + ${level} * ${LEVEL_INDENT})`;
// A column holds the connector of the ancestor one level deeper, so
// its line runs past this row while that ancestor has a sibling
// below. The current item's own connector column (nestedLevel - 1)
// is rendered below with its terminus or continuation style.
const continues =
level < nestedLevel - 1 && !ancestorsIsLast[level + 1];
return (
// Skip the level that the current-item connector occupies
// (nestedLevel - 1), since that position is rendered below
// with the correct terminus/continuation style.
!ancestorIsLast &&
level !== nestedLevel - 1 && (
continues && (
<div
// eslint-disable-next-line @eslint-react/no-array-index-key -- tree branch levels are fixed positional connectors
key={level}
Expand Down
24 changes: 12 additions & 12 deletions packages/core/src/TreeList/TreeListItem.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -93,9 +93,9 @@ const styles = stylex.create({
// 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
// stay contiguous, because the gap is padding inside each <li>, not space
// between them. So the per-row connector guide can still span it and read
// as one 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)',
Expand Down Expand Up @@ -712,16 +712,16 @@ export function TreeListItem({
data-tree-level={nestedLevel + 1}
data-tree-disabled={isDisabled || undefined}
{...focusOutlineProps.publishFocusVisibleVars(styles.wrapper)}>
{variant !== 'noGuides' && (
<div {...stylex.props(styles.treeBranches)}>
<TreeListBranches
ancestorsIsLast={ancestorsIsLast}
isLast={isLast}
nestedLevel={nestedLevel}
/>
</div>
)}
<div {...stylex.props(styles.rowWrapper)}>
{variant !== 'noGuides' && (
<div {...stylex.props(styles.treeBranches)}>
Comment thread
astracat-bot[bot] marked this conversation as resolved.
Resolved
Comment thread
astracat-bot[bot] marked this conversation as resolved.
Resolved
<TreeListBranches
ancestorsIsLast={ancestorsIsLast}
isLast={isLast}
nestedLevel={nestedLevel}
/>
</div>
)}
<div
{...(isInteractive || (hasChildren && onClick == null)
? pressable
Expand Down
Loading
Loading